Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access a Grails variable in JavaScript?

I have a variable in my Grails app’s BootStrap.groovy:

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

I want to show a 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 a Grails class in Javascript to do the above?

Thanks.

like image 260
junaidp Avatar asked Dec 12 '22 07:12

junaidp


2 Answers

First of all - you have to make this variable accessible from other places. Currently it's bounded to init scope. You can put it into global config for example (see Config.groovy). Or set to an service. Or make an public static variable somewhere.

Example for a service:

class VariableHOlderService {

    def testGrails

}

and

class BootStrap {

      VariableHolderService variableHolderService

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

Second - you need to put it into request. There is two ways - use filter or controller/action. First option is useful when you want to use same variable from different GSP.

From controller it would be:

VariableHolderService variableHolderService

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

and use it at GSP as

<g:javascript>
       if(${testGrails}==11)   
       {
           alert("yes");
       }    
</g:javascript>
like image 53
Igor Artamonov Avatar answered Dec 24 '22 05:12

Igor Artamonov


You should define your variable in Config.groovy, not in Bootstrap. Then you can access it in gsp files like this:

       <SCRIPT LANGUAGE="JavaScript">
       if(${grailsApplication.config.testGrails}==11)
       {
           alert("yes");
       }        
like image 34
socha23 Avatar answered Dec 24 '22 04:12

socha23