我认为在grails标记中解析变量时遇到了一些困难。
在我的标签库中
def contentArea = {attrs, body ->
def domainObject = Class.forName("${attrs.contentType}", true, Thread.currentThread().contextClassLoader).newInstance()
def numberOfRows = !StringUtils.equals("${attrs.max}", "null")? new Integer("${attrs.max}") : new Integer("1");
def results = domainObject.getByContentAreaKey("${attrs.contentAreaKey}", numberOfRows)
out << g.render(
template: '/layouts/contentTag',
model: [contentAreaKey: attrs.contentAreaKey, results : results, contentNamespace: "${attrs.contentAreaKey}" + "_contentList", body:body()])
out << body()
}
在_contentTag.gsp中,布局为:
<b>In tag layout, </b>
<g:set var="${contentNamespace}" value="bobby"/>
contentNamespace = ${contentNamespace}<br/><!-- prints "minicontent_contentList" -->
minicontent_contentList = ${minicontent_contentList}<br/> <!-- prints "bobby" -->
在调用gsp中,该标签称为:
<mynamespace:contentArea var="myVar" contentAreaKey="minicontent" contentType="com.my.test.MiniContentType">
<br/>Test Text<br/>
<b>in calling GSP,</b>
contentNamespace = ${contentNamespace}<br/><!-- prints nothing -->
minicontent_contentList = ${minicontent_contentList}<br/><!-- prints nothing -->
</mynamespace:contentArea>
在标签正文中未解析contentNamespace和minicontent_contentList。变量是否可以解析?如果是这样,我该怎么办?
如果它有助于解决问题,那么我的页面上会有许多小内容区域,我希望能够通过其他 Controller 进行管理。内容区域后面都有相似的数据(文本,链接,图形等),但是布局会有所不同。我已经使用sitemesh布局来屏蔽该页面,并且调用gsp代表这些sitemesh内容块之一。
我是新手,希望获得SO方面的帮助,所以我很愿意接受批评,但请保持谦虚。 :)
最佳答案
传递给参数的body
是Closure
,它将其方法和参数解析到声明它的位置,这里将是主要gsp。您可以尝试将delegate
的body
设置为标签库,并将resolveStrategy
设置为Closure.DELEGATE_FIRST
。这应该允许您解析contentNamespace
。
def contentArea = {attrs, body ->
...
def contentNamespace = "${attrs.contentAreaKey}" + "_contentList"
out << g.render(
...
body.delegate = this
body.resolveStrategy = Closure.DELEGATE_FIRST
out << body()
}
解决
minicontent_contentlist
会比较困难,因为我不确定如何将模板指定为委托(delegate)。您可以尝试在标签库中定义变量并将其传递给模板模型,然后将minicontent_contentlist
值分配给该传递的对象,这可以将标签库代码中的值更新回以使resolveStrategy
正常工作,假设它是通过引用传递的同一对象。def contentArea = {attrs, body ->
...
def minicontent_contentList
out << g.render( ..., model:[minicontent_contentList:minicontent_contentList])
...delegate and resolveStrategy stuff...
}
<b>In tag layout, </b>
<g:set var="minicontent_contentlist" value="bobby"/>
contentNamespace = ${contentNamespace}<br/><!-- prints "minicontent_contentList" -->
minicontent_contentList = ${minicontent_contentList}<br/> <!-- prints "bobby" -->
作为最后的选择,您可以尝试在模板的gsp curlies(
delegate/resolveStrategy
)中分配${}
,以查看是否将模板对象分配给delegate
参数。