Passing Localized Javascript Messages From Resource Bundles Using Jsf
I have built an application with JSF and all messages issued by the server are localized with resource bundles. My question is: how to get messages issued in the client browser wit
Solution 1:
Just let JSF print the desired JS code. E.g.
<script>var message = "#{bundle['some.key']}";
</script>
You only need to take JS special characters such as singlequotes and newlines into account. For that, you could register a custom EL function which delegates to Apache Commons LangStringEscapeUtils
, or use OmniFacesof:escapeJS()
function.
Solution 2:
if you want to provide all keys use something like that in yout main-template etc.
<scripttype="text/javascript">var msg = newObject();
<c:forEachitems="#{msg.keySet()}"var="key">
msg.#{key} = "#{msg[key]}";
</c:forEach></script>
Solution 3:
the wutzebaer answer is right but it has a problem when then the variables of a literal has any dot, like "person.name"
<script type="text/javascript">
var msg = newObject();
<c:forEach items="#{msg.keySet()}"var="key">
try{
//msgTempl.#{key} = "#{msg[key]}";
msg['#{key}'] = "#{msg[key]}"; //works better than msgTempl.#{key} = "#{msg[key]}"; when the key contains dots like 'fields.name'
}catch(e){
console.log("error fullfilling the msgForms resource from bundle " +e);
}
</c:forEach>
</script>
that worked for me, but the netbeans shows this error:
Error: Theprefix"c"for the "c: forEach" element is not linked.
cause it had put a JSTL tag insida a script, but it works fine, however
also there is another way to do it
@ManagedBean(name = "ResouceBundle")
@ApplicationScopedpublicclassResouceBundleimplementsSerializable {
privatestatic final long serialVersionUID = 1L; //needed because the bean is application|session|view and it needs to be SerializablepublicString msg;
@PostConstructpublicvoidinit() {
this.msg = createResourceBundleJSON("resourceName");
}
publicStringcreateResourceBundleJSON(String resourceName) {
FacesContext context = FacesContext.getCurrentInstance();
ResourceBundle bundle = context.getApplication().getResourceBundle(context, resourceName);
JSONObject jsonObj = newJSONObject();
Set<String> keys = bundle.keySet();
for (String key : keys) {
jsonObj.put(key, JSONObject.wrap(bundle.getString(key)));
}
return jsonObj.toString();
}
publicStringgetMsg() {
return msg;
}
publicstatic long getSerialVersionUID() {
return serialVersionUID;
}
}
and then, in the XHTML, just write:
<script type="text/javascript">
var msg = #{ResouceBundle.msg}
</script>
Post a Comment for "Passing Localized Javascript Messages From Resource Bundles Using Jsf"