I'm using a GSP for sending out emails based on the MailService plug-in. The sendMail closure passes (amongst others) body(view:..., model:myModel)
I know that I can access every item of the myModel Map just using ${itemName}
in the GSP. However as I sometimes want to build the item name dynamically like 'item'+i
, I need to have some surrounding method to access the variable.
I already tried ${model.get('item'+i)
, and ${params.get('item'+i)
, but model is null and params is an empty Map. I also tried pageScope, but though I can access an item via ${pageScope.itemName
, I can not use ${pageScope.get('item'+i)}
because pageScope is not a Map.
Probably there are multiple solutions to solve this; I'd be glad about an easy one ;-). One solution I see is to pass myModel as the only parameter and then always use myModel.get(...)
, however this would mean that I had to change all my existing GSPs to always refer to myModel instead of accessing items (with fixed names) directly; so if there's a way where I don't have to change the model passed to the GSP, this would be my favorite.
If someone could also say a few words about the difference of model and params in this context, this would be additionally helpful!
I've managed it now using ${pageScope.getProperty(...)}
.
There's no 'model' scope or variable. Instead objects in the model map are set as Request attributes to make them available to the GSP. This is a Spring feature which makes it easy to access variables in JSPs using JSTL and since the GSP syntax is very similar to JSTL it works the same way in Grails.
So you can use this:
${request.getAttribute('item'+i)}
to access model variables using dynamic names.
You can use ${fieldValue(bean: book, field: 'title')}
See: http://grails.github.io/grails-doc/latest/ref/Tags/fieldValue.html
来源:https://stackoverflow.com/questions/3810844/how-to-reference-a-grails-gsp-model-variable-indirectly-e-g-via-get