0

I recently started learning grails and I am trying to use a gsp variable declared in the layout of the page as:

<g:set var="abtestType" value="newSearchBar" />

in the js file that is being loaded on the same page. Things that I have tried:

 alert(${abtestType});  
 alert(<%=abtestType%>);
 alert("abtestType:"+abtestType);

but its showing error as variable is not defined. Probably I am trying to fetch it in wrong way, need help regarding this.

Tomasz Jakub Rup
  • 9,464
  • 7
  • 44
  • 47
Rajeev Dixit
  • 1,313
  • 2
  • 15
  • 25

1 Answers1

1

Even thinking about doing so neither makes sense nor applicable.

Reason for such statement is that when a gsp page is rendered to an html page, it replace grails tags with appropriate html tags or value. Similarly it replaces the ${} or <%%> with html or javascript or whatever that goes on front-end.

Hence the code that you have tried could have worked fine if you were having those javascript code lines in the gsp itself but as you have called externalised js file it actually don't know anything about gsp or jsp or any other Language's front-end support.

The one way of doing that if using global variable in javascript. e.g.

declare abtestType above like below:

<script>
var abtestType = "${abtestType}"
</script>

Now you have access to global variable abtestType in your javascript.

Use it in your javascript but remember now you need to have this variable iff the code using it is called otherwise very same error would you get i.e. variable is not defined

There is another way that I found in this post but is a manipulation actually.

Is there any analogue in Javascript to the __FILE__ variable in PHP?

Also, another good links is

Pass vars to JavaScript via the SRC attribute

Hope it helps!

Community
  • 1
  • 1
Vinay Prajapati
  • 6,025
  • 4
  • 36
  • 75