7

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

}

3 Answers 3

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>
Sign up to request clarification or add additional context in comments.

5 Comments

will we need that quotes in "${x}". ?..what about just ${x}.
@AhmadBeg depends on type of your variable contents. If it is string, you should quote it, if it is integer or float, you can deal without quotes. This is basic JavaScript.
it didn't work...it just printing ${x} not value of x...tried without quoted even
@AhmadBeg yes, you should have placed myvariable in place of x. My mistake. But you should really read the referance manual for freemaker, this is variable basics.
That should be "${myvariable?js_string}", or else you will have a problem if the variable contains quotation marks, line-breaks, etc.
5

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> 

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.