【问题标题】:How does Grails know to apply a "layout" to pages it renders?Grails 如何知道将“布局”应用于它呈现的页面?
【发布时间】:2010-11-17 02:01:27
【问题描述】:

我一直在阅读“Grails 权威指南”(Rocher/Brown)一书,在第 4 章中,这个被称为“布局”的神秘事物刚刚出现,没有任何解释。 (并且索引中没有“布局”。据我所知,从未解释过。)

系统如何知道从 layout/main.gsp 中“继承”页面?索引中没有关于“布局”的内容,它似乎刚刚出现。

在他们的示例应用程序上,一个简单的商店网站,/主页的 URL 映射说

  "/"(controller:"store")

并存储控制器的空“索引”闭包

package com.g2one.gtunes

class StoreController {

    def index = {
    }
}

只是告诉它渲染 store/index.gsp

store/index.gsp 只有几行 HTML;任何指令都不包含布局

<html>
    <head>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8">
        <meta name="layout" content="main">
        <title>gTunes Store</title>
        <g:javascript library="prototype"></g:javascript>
    </head>
    <body id="body">
        <h1>Your online music store and storage service!</h1>
        <p>Manage your own library, browse music and purchase new tracks as they become available</p>
    </body> 
</html>

当我运行示例时,为“/”显示的页面不仅仅是这个简单的 HTML,它是“layouts/main.gsp”的内容,其中神奇地插入了这些信息。

我看不到 layout/main.gsp 中的信息是如何应用到页面的,元素是如何混合在一起的。我一直在逐页阅读这本书,而这个功能只是“出现”而没有任何解释。

【问题讨论】:

    标签: grails layout


    【解决方案1】:

    &lt;meta name="layout" content="main"&gt; 标签包含 gsp 页面中的布局。

    您可以查看grails-app/views/layouts/main.gsp 来查看和修改布局。您可以将main.gsp 复制到mymain.gsp,对其进行修改,然后将gsp 页面中的布局条目更改为引用mymain.gsp 而不是main.gsp,并尝试自定义您的布局,保留您轻松撤销更改的能力。

    Grails 在后台使用sitemesh(就像它使用hibernate 和spring 一样)来进行视图布局。项目目录下还有一个web-app/WEB-INF/sitemesh.xml 配置文件。这个特定的文件没有那么有用,但是如果您想深入了解 grails 如何使用 sitemesh,它会引用 groovy 项目中的一个类(这可能不是必需的)。

    【讨论】:

    • 谢谢!它正盯着我的脸。当所有其他 grails 指令看起来像 时,我没想到要查看“元”标签
    【解决方案2】:

    这是你的指令:

    <meta name="layout" content="main">
    

    main.gsp 包含&lt;g:layoutHead&gt;&lt;g:layoutBody&gt;,其中index.gsp 的&lt;head&gt;&lt;body&gt; 内容被折叠到布局中以创建最终页面。

    【讨论】:

      【解决方案3】:

      最近出现了一个有效的技巧,如果您将布局命名为与控制器匹配,它会出现(至少在 Grails 2.3.4 中)自动使用该模板。

      例如我的控制器:

      // grails-app/controllers/myapp/HomeController.groovy
      package myapp
      class HomeController {
          def index() {
              [ myvar: "Test" ]
          }
      }
      

      我的布局:

      // grails-app/views/layouts/home.gsp
      <html>
        <head></head>
        <body>
          <h1>Home</h1>
          <g:layoutBody />
        </body>
      </html>
      

      我的看法:

      // grails-app/views/home/index.gsp
      <p>${ myvar }</p>
      

      使用主布局进行渲染。

      此外,您可以在控制器中为所有操作指定布局,如下所示:

      class HomeController {
          static layout = "someotherlayout"
      
          // actions will render using grails-app/views/layouts/someotherlayout.gsp
      }
      

      【讨论】:

      • 感谢您的提示!当一个 AJAX 加载的 gsp 被自动包装时,我被这个咬了。有一个带有控制器名称的布局。
      猜你喜欢
      • 1970-01-01
      • 2019-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-24
      相关资源
      最近更新 更多