admin管理员组

文章数量:1202370

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 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);

}
Share Improve this question asked Feb 4, 2013 at 8:13 Ahmad BegAhmad Beg 4,5353 gold badges15 silver badges5 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 13

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(); }
});

本文标签: use freemarker variable in javascriptJqueryStack Overflow