GSP / Groovy -g:每个都包含对象数组

时间:2015-12-21 16:01:18

标签: grails groovy gsp

我试图在地图上使用g:each代码,但GSP无法识别它。

代码是:

    if(previousQuestions == null)
    {
        previousQuestions = []
    }
    def obj = AnimaisTreeMap.get(curNode)

    previousQuestions.push('question':obj.nodeDescription, 'answer': getDescOptionAnswer(optionAnswered))

g:每个标签都是:

<g:each in="${previousQuestions}" var="row" status="i">
    <div>
        <label>${row.question}</label>
        <label>${row.answer}</label>                            
    </div>
    <br/>
</g:each>       

输出结果为:

[{question=vive na água, answer=Não}, {question=tem listras, answer=Sim}]

据我所知g:每个读取的对象可能是JSON格式&#34;属性:值&#34;但我的目标是&#34; property = value&#34;

我该如何解决?

已更新

看到this link后,我找到了解决方案。问题本身就是&#34;前进&#34;功能,我通过&#34; previousQuestions&#34;另一个行动。而不是&#34; params&#34;,正确的方式是&#34; model&#34;。

        forward(action:'index', model: [curNode: nextNode.id,
                                        previousNode: curNode, 
                                        curQuestion: curQuestion,
                                        previousQuestions: answersTrace])                   

当我需要恢复&#34; previousQuestions&#34;时,我必须使用&#34; request&#34;在控制器上注入对象。在此之后,我的代码没问了

1:此链接

2 个答案:

答案 0 :(得分:1)

每次拨打push()时,您似乎都会添加两张地图。尝试创建要添加到地图数组的每个地图,而不是仅传递单独的键值对。

我相信这就是你想要的:

previousQuestions.push(['question':obj.nodeDescription, 
                        'answer': getDescOptionAnswer(optionAnswered)])

答案 1 :(得分:0)

试试这个:

//This is a far better way of checking null strings 
//shorter and also checks for '' as well as null
if(!previousQuestion)  {
   previousQuestions = []
} else {
   //this segment you have not provided so as a test ensure it 
   //matches List element above that you have declared - take a look at console
   println "this is probably your issue ${previousQuestions.getClass()} what is class here ????"
}

def obj = AnimaisTreeMap.get(curNode)

// generate a map on the fly good for iterations, 
// even though this is not iterated.

previousQuestions << ['questions': obj.nodeDescription as String, 
'answer':  getDescOptionAnswer(optionAnswered) as String]

//within genrated map above the elements have been converted to as String 
// Because you have not given the workings of getDescriptionAnswer
// in theory you should not need  as String this is just for testing

render (view: 'something', model: [previousQuestions:previousQuestions])