Ahmad Beg
Ahmad Beg

Reputation: 4545

use freemarker variable in javascript/Jquery

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

}

Upvotes: 7

Views: 35791

Answers (3)

Sagar Kale
Sagar Kale

Reputation: 97

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> 

Upvotes: 5

jpllosa
jpllosa

Reputation: 2202

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

Upvotes: 1

Deele
Deele

Reputation: 3684

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>

Upvotes: 13

Related Questions