在我的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的分配不起作用:当我收到http://localhost:8080/myApp/aView.gsp时,bar断言失败
org.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中的变量传递到共享模板中,然后可以考虑如下。我这样做是为了在我的公共(public)标题中隐藏“登录”链接(如果它们位于login.gsp页面上)

<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/

10-11 23:28
查看更多