I have declared a variable in freemarker as
<#assign myvariable= "value">
I want to access it in my javascript function like as follows
function myfunction(){
alert(myvariable);
}
I guess, at first, you should output that variable into your HTML/JavaScript code, something like this:
<script type="text/javascript">
var myvariable = "${myvariable}";
function myfunction(){
alert(myvariable);
}
</script>
You can assign freemarker variable to HTML input field and access it in JavaScript using jquery or document Here how it is
<input id=“freemarkervar” type=“text or hidden” value=“${myVariable}”/>
<script type="text/javascript">
var val = $(“#freemarkervar”).val();
alert(val);
// using JavaScript
var val=document.getElementById("freemarkervar").value;
alert(val);
</script>
You can use FreeMarker code in JavaScript straight away. Here's a sample code where FreeMarker supplies the data of a Morris.js chart. I think you'll get the idea.
new Morris.Area({
element: 'searchTrend',
resize: true,
data: [
<#list searchCount as sc>
{day: '${sc.date!?string("yyyy-MM-dd")}', count: ${sc.searches}} <#sep>,
</#list>
],
xkey: 'day',
ykeys: ['count'],
labels: ['Count'],
xLabelFormat: function (x) { return x.getDate(); }
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With