How can I access the Grails variable in JavaScript?

I have a variable in my Grails BootStrap.groovy applications:

  class BootStrap { def init = { servletContext -> def testGrails = "11" 

I want to show JavaScript alert() if this test value is 11.

My JavaScript:

  <SCRIPT LANGUAGE="JavaScript"> if(testGrails==11) // WHAT TO WRITE WITH IN THE BRACKETS ...? { alert("yes"); } 

How can I access the Grails class in Javascript to do this?

Thanks.

+4
source share
3 answers

First of all, you must make this variable available from other places. It is currently limited to the init area. You can put it in a global configuration, for example (see Config.groovy ). Or install the service. Or make the variable public static somewhere.

Example for service:

 class VariableHOlderService { def testGrails } 

and

 class BootStrap { VariableHolderService variableHolderService def init = { servletContext -> VariableHolderService.testGrails = "11" } 

Secondly - you need to put it in the request. There are two ways - to use a filter or a controller / action. The first option is useful if you want to use the same variable from different GSPs.

From the controller, it will be:

 VariableHolderService variableHolderService def myAction = { render model: [testGrails:variableHolderService.testGrails] } 

and use it in gsp as

 <g:javascript> if(${testGrails}==11) { alert("yes"); } </g:javascript> 
+9
source

You must define your variable in Config.groovy, not Bootstrap. Then you can access it in gsp files as follows:

  <SCRIPT LANGUAGE="JavaScript"> if(${grailsApplication.config.testGrails}==11) { alert("yes"); } 
+2
source

Are you sure you need it at Bootstrap.groovy ? Is that what you expect or can change?

If your answer is no, I found that the meta tag is very useful for getting information in GSP files.

For example, if you want to specify your application name, you can do it like this:

 <g:meta name="app.name"/> 

You can get any property in your application.properties file.

And if you, like me, must combine it with a different value, here is my example. Remember that any tag can be used as a method without the g: namespace. For instance:

 <g:set var="help" value="http://localhost:8080/${meta(name:"app.name")}/help" /> 

The Grails documentation about this is a bit poor, but here .

+1
source

Source: https://habr.com/ru/post/1381890/


All Articles