Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference a grails GSP model variable indirectly e.g. via .get(...)

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!

like image 285
Jörg Brenninkmeyer Avatar asked Dec 28 '22 07:12

Jörg Brenninkmeyer


2 Answers

I've managed it now using ${pageScope.getProperty(...)}.

like image 109
Jörg Brenninkmeyer Avatar answered Jan 25 '23 19:01

Jörg Brenninkmeyer


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.

like image 25
Burt Beckwith Avatar answered Jan 25 '23 21:01

Burt Beckwith