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.

Answers


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).

messages_fr_FR.properties

hi.message=Bonjour

messages_en_GB.propertie

hi.message=Hello

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.

I encourage you to check all the available springmvc velocimacros and velocity tools (very useful!).


Need Your Help

How can I interrupt a sequence of procedures in Java?

java multithreading exception lejos-nxj

I have a bunch of procedures that need to be executed successively until either they are all executed, or a certain condition is met. Here's the basic code that needs to be executed until a conditi...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.