在我的 Grails 1.3.7 应用程序中,我想使用模板从 View 中分解出周围的 HTML。但是,GSP 变量赋值在包含的 body() 中不起作用。我怎样才能做类似以下的事情?
_aTemplate.gsp:
<div class="example">
<% out << body() %>
</div>
aView.gsp:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="layout" content="main" />
</head>
<body>
<g:set var="foo" value="${42}"/>
<% assert foo == 42 : foo %>
<tmpl:/aTemplate>
<g:set var="bar" value="${6}"/>
<% assert bar == 6 : bar %>
</tmpl:/aTemplate>
</body>
</html>
bar
的分配不起作用:bar
断言失败,当我得到 http://localhost:8080/myApp/aView.gsporg.codehaus.groovy.grails.web.taglib.exceptions.GrailsTagException:
Error executing tag<g:render>: Assertion failed:
(bar == 6). Values: bar = null
at /Users/jbeutel/proj/grailsSandboxes/myApp/grails-app/views/aView.gsp:13
如何使模板 body() 正常工作?
或者,有没有其他方法可以在保持平衡的同时分解周围的 HTML?我的用例不在顶层,所以我没有尝试使用布局。如果我使用 TagLib 闭包而不是模板文件,则变量分配有效,但我不想将大量 HTML 放入闭包中,因此无论如何我都需要将不平衡的 HTML 放入模板文件中(即,之前的单独模板和 body 之后)。有没有更好的办法?
最佳答案
您可以将 .gsp 中的变量传递到共享模板中,然后可以按如下方式考虑。如果它们在 login.gsp 页面上,我这样做是为了在我的公共(public)标题中隐藏一个“登录”链接
<g:render template="/layouts/header" model="['hidelogin':true]"/>
然后在 _header.gsp
<g:if test="${!hidelogin}">
//show your login link
</g:if>
关于templates - 如何在 Grails 模板 body() 中分配 GSP 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6431174/