开发者

iterate over Grails controller model

开发者 https://www.devze.com 2023-02-20 09:23 出处:网络
Say I have a controller action like the following: def someAction = { if (someCondition) { [foo: 1, bar: 2]

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?


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}">


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消