aahmed31
aahmed31

Reputation: 39

Assign JavaScript function value to a Freemarker variable

I have a JavaScript function in my Freemarker file as follows:

<script type="text/javascript">
  function myFunc(){
    var myString = "I like pizza";
    return myString;
  }
</script>

I am trying to assign the myString return value from myFunc to myVar in Freemarker as follows:

<#assign myVar = myFunc()>

Unfortunately, the value of myVar is an ampty String (""). What am I doing wrong?

Upvotes: 0

Views: 3758

Answers (2)

ddekany
ddekany

Reputation: 31152

FreeMarker runs on the web server, while the JavaScript runs in the browser later. So you should end up with an error where FreeMarker complains that there's no such thing as myFunc. No idea how you end up with an empty string in myVar instead (maybe there's some more oversight related to that), but in any case, what you trying to do won't work.

Upvotes: 1

Aswin
Aswin

Reputation: 147

You are trying to return myString from myFunc(). Where you have defined myString? Is it in a parent scope of myFunc()? If it is not, there are two possible scenarios!

  • Scenario 1: Non-Strict mode - A new myString variable is created and will be returned, which is a possible cause for your problem of empty String!
  • Scenario 2: Strict mode - Variable myString will be returned as undefined, which is not your case.

Possible Solutions - Instantiate the variable using some values in parent scope or current scope of myFunc()

Edited

I am afraid to see that freemaker templates would be compiled in server. Alternative solution is to include the entire freemaker call-site in script tag, so that it will work based on client side instance, if you need a JavaScript in that template after compiled to scriptin client's browser.

Upvotes: 0

Related Questions