Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

Mixing JSF EL in a JavaScript file

Is there a way to have Expression Language (EL) expressions included JavaScript files be evaluated by JSF?

I was hoping that Seam might have a way around this, but no luck so far. All I want is to be able to use localized messages in my JavaScript functions which are shared across pages.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Five ways:

  1. Declare it as global variable in the parent JSF page.

    <script type="text/javascript" src="script.js"></script>
    <script type="text/javascript">
        var messages = [];
        <ui:repeat value="#{bean.messages}" var="message">
            messages['#{message.key}'] = '#{message.value}';
        </ui:repeat>
    </script>
    

    Or, if it's in JSON format already.

    <script type="text/javascript" src="script.js"></script>
    <script type="text/javascript">var messages = #{bean.messagesAsJson};</script>
    
  2. Put the whole <script> in a XHTML file and use ui:include to include it.

    <script type="text/javascript" src="script.js"></script>
    <ui:include src="script-variables.xhtml" />
    
  3. Pass *.js through the JspServlet (only if it's enough to evaluate only the ${} expressions). E.g. in web.xml (the <servlet-name> of JspServlet can be found in web.xml of the servletcontainer in question, it's usually jsp).

    <servlet-mapping>
        <servlet-name>jsp</servlet-name>
        <url-pattern>*.js</url-pattern>
    </servlet-mapping>
    
  4. Make use of "good old" JSP with a modified content type. Rename script.js to script.jsp and add the following line to top of JSP (only if it's enough to evaluate only the ${} expressions):

    <%@page contentType="text/javascript" %>
    
  5. Let JS obtain the data ajaxically during load. Here's a jQuery targeted example.

    $.getJSON('json/messages', function(messages) {
        $.each(messages, function(key, value) {
            $.messages[key] = value;
        });
    });
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...