Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically evaluate an el expression

Tags:

grails

groovy

How can I get the value of el expression dynamically in an controller. For eq.

class ElController {
  def index() = {
    def a = "\${1 + 3}"
    unknownElEvaluator(a) // ->"2"
    ....
  }
}
like image 729
DraganS Avatar asked Mar 14 '26 12:03

DraganS


1 Answers

You can do that with the Groovy SimpleTemplateEngine:

import groovy.text.SimpleTemplateEngine

def binding = [:]
def a = "\${1 + 3}"
String rslt = new SimpleTemplateEngine().createTemplate( a )
                                        .make( binding )
                                        .toString()
assert rslt == '4' // 4 not 2 as in your question

Though it would be interesting to know why you'd be doing this in a controller...

Alternatively, you should be able to add:

def groovyPagesTemplateEngine

To your controller (or preferably as separate Service class, as you may end up wanting to do this from more than one place in your code)

Then, from inside the method, do:

def binding = [:]
def a = "\${1 + 3}"

String rslt = new StringWriter().with { writer ->
  groovyPagesTemplateEngine.createTemplate( a, 'myscript' )
                           .make( binding )
                           .writeTo( writer )
  writer.toString()
}
like image 177
tim_yates Avatar answered Mar 17 '26 02:03

tim_yates



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!