Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

}
like image 850
Ahmad Beg Avatar asked Feb 04 '13 08:02

Ahmad Beg


3 Answers

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>
like image 59
Deele Avatar answered Oct 02 '22 18:10

Deele


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> 
like image 25
Sagar Kale Avatar answered Oct 02 '22 18:10

Sagar Kale


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(); }
});
like image 29
jpllosa Avatar answered Oct 02 '22 16:10

jpllosa