Dónal
Dónal

Reputation: 187499

iterate over Grails controller model

Say I have a controller action like the following:

def someAction = {

    if (someCondition) {
        [foo: 1, bar: 2] 
    } else {
        [foo2: 4, bar2: 6, baz2: 6]
    }
}

In someAction.gsp I don't know what the keys of the model are. Is there some way that I can iterate over the keys and values of the model without knowing the key names?

Upvotes: 3

Views: 908

Answers (2)

mdlandon
mdlandon

Reputation: 125

Use pageScope:

<ul>
    <g:each var="item" in="${pageScope.variables}">
        <li>${item.key} = ${item.value}</li>
    </g:each>
</ul>

But note that you won't be able to distinguish between the controller model values and those from the framework.

Upvotes: 1

deluan
deluan

Reputation: 1865

All model attributes are available in the request object. You can iterate this object like this:

    <g:each var="item" in="${request}">
      ${item.key} = ${item.value}<br/>
    </g:each>

Note that the request object will hold all request attributes, a lot of information that you're probably not interested in.

Another way to accomplish what you want is putting all your model attributes in one map, like this:

    if (someCondition) {
       [result:[foo: 1, bar: 2]] 
    } else {
       [result:[foo2: 4, bar2: 6, baz2: 6]]
    }

This way you can isolate your attributes from other request attributes. In this case you'll have to iterate your model keys using the result map:

    <g:each var="item" in="${result}">

Upvotes: 6

Related Questions