Results 1 to 1 of 1

Thread: How to get i18n messages in javascript

  1. #1
    Join Date
    Jul 2005
    Posts
    156

    Default 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 !
    Attached Files Attached Files

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •