I was wondering if anyone out there knew of a way to have EL expressions in 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.
+4
A:
Four ways:
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 items="#{bean.messages}" var="message"> messages['#{message.key}'] = '#{message.value}'; </ui:repeat> </script>
Put the whole
<script>
in a XHTML file and useui:include
to include it.<script type="text/javascript" src="script.js"></script> <ui:include src="script-variables.xhtml" />
Pass
*.js
through theJspServlet
(only if it's enough to evaluate only the${}
expressions). E.g. inweb.xml
(the<servlet-name>
ofJspServlet
can be found inweb.xml
of the servletcontainer in question, it's usuallyjsp
).<servlet-mapping> <servlet-name>jsp</servlet-name> <url-pattern>*.js</url-pattern> </servlet-mapping>
Make use of "good old" JSP with a modified content type. Rename
script.js
toscript.jsp
and add the following line to top of JSP (only if it's enough to evaluate only the${}
expressions):<%@page contentType="text/javascript" %>
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; }); });
BalusC
2010-03-30 19:04:34
I might add that the first one is the easiest. Let Facelets handle it for you.
Shervin
2010-03-31 08:30:42
Thanks I used the first one.
2010-04-01 20:50:37