Is it possible to read static text dynamically from property files in velocity template?
greetings all i have a java ee application (spring framework) that uses vm templates that contains static texts like:
<span> hello world </span>
to be something like:
<span> <fmt:message key="hi.message" /> </span>
and i was wondering if it's possible to read that texts from a property file(en/fr) depending on the user locale like in JSP, so that i will use one template for all locales and the text is dynamic
Note: velocity is not my view technology used in the app, i am using it's templates in sending emails only.
Spring MVC comes with (very) useful velocimacros (see Spring MVC documentation). One of them is #springMessageText.
In your hello.vm file:
<span>#springMessageText("hi.message", "Hello Default!")</span>
This macro will read the message from your message sources, depending on the current locale (using the built-in ResourceBundleMessageSource from Spring).
If no bundle is available for the current locale, the default message "Hello Default!" is used.
By default, Spring is reading messages*.properties files. But you can specify more message sources in your servlet.xml configuration (here, messages*.properties and othermessages*.properties):
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basenames"> <list> <value>messages</value> <value>othermessages</value> </list> </property> </bean>
How does SpringMVC knows about the current locale?
Well, it's all built-in SpringMVC. The ResourceBundleMessageSource reads keys according to the Locale. I think a LocaleResolver is configured by default (using the locale sent along the client request), but you can register your own localeResolver.