Announcement Announcement Module
Collapse
No announcement yet.
How to get i18n messages in javascript Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • How to get i18n messages in javascript

    Hello,

    This thread is just to share some code. Hope it will help someone.

    With this solution you'll have an easy access to messageSource content from your javascript.

    Solution out of the box
    Solution provided out of the box by Spring MVC or JTL is to use <fmt:message key="date_format_js"/> or <spring:message code="date_format_js"/>.
    This is fine if : you're in a JSP file, if you use a few i18n labels, but it's a pain IMO if you're working in a JS file (you need to transform it to a JSP file) and if you have a lot of i18n vars.

    Solution in this thread
    The attached code allows to export some (or all) of the content of the messageSource as a JS file.
    By default, it's just a JSON structure defined in a javascript variable : messages.

    Sample usage :
    Just include the attached files into your project and make sure you have the corresponding context:component-scan.
    JSP file
    :
    Code:
    <c:set var="ctx" value="${pageContext['request'].contextPath}"/>
    <script type="text/javascript" src="${ctx}/1.0.0/messages-${global_locale}.js"></script>
    <script type="text/javascript">
    alert (messages.date_format_js);
    </script>
    Spring configuration :
    Basic configuration, just make sure you declare a messageSource bean, i.e. :
    Code:
    <bean
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource"
        id="messageSource">
        <property name="basenames"
            value="WEB-INF/i18n/messages,WEB-INF/i18n/application" />
        <property name="fallbackToSystemLocale" value="false" />
        <property name="cacheSeconds" value="3" />
    </bean>
    Problems
    This code is thightly coupled with Spring messageSources implementation API.
    To resolve this issue, I would need an API in MessageSource interface to get all messageSource keys.


    Hope this can help someone !

  • #2
    Yes sir! It's a great piece of code and helped me a lot. I've wondered why it's not out of the Spring box :-)

    Just one note to help future users: you'll have a problem to @RequestMapping *.js extension if you use static resources and default servlet-mapping in web.xml:

    <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>*.html</url-pattern>
    </servlet-mapping>

    You need to add for examle something like this:
    <url-pattern>/locale/*</url-pattern>
    and use @RequestMapping in MessagesController _without_ the /locale/.

    Adding only <url-pattern>*.js</url-pattern> to the servlet-mapping causes broken links for static resources!

    Thanx
    Last edited by KrzysiekWu; Nov 15th, 2013, 01:48 PM.

    Comment

    Working...
    X