Thursday, November 1, 2012

JSTL: How to access fmt:message from Javascript


You might have seen How to use fmt:message and ResourceBundle from JSP and Java in my earlier post, click here.

Now we will see how to use fmt:message from Javascript. Its very simple to use JSTL's fmt tag in JavaScript to localize alert messages.

I found two ways in which you can access values from a property file in javascript. Please see the sample codes below.

Method 1.

<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<script type="text/javascript">
<!--
var msg = {
prop1: "<fmt:message key="prop1" />",
prop2: "<fmt:message key="prop2" />"
};

function test() {  
 alert(msg.prop1);
alert(msg.prop2);
}

//-->
</script>

Method 2.

<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<script type="text/javascript">
<!--
<fmt:message key="prop1" var="prop1"/>    
var prop1 = "${prop1}";

function test() {  
 alert(prop1);
}

//-->
</script>

1 comment: