grails 3 中的动态布局选择

问题描述

使用 sitemesh 可以为相同的页面使用不同的布局。例如对于移动和 PC 用户

但是如何用 grails 做到这一点呢? 在 documentationarticle 中没有写任何关于这个案例的内容 我在 view.gsp 中尝试过标记,但不起作用

<Meta name="layout" content="${defineLayout()}"/>

有什么想法吗?

解决方法

您可以使用任何动态表达式来表达布局的名称。例如...

function App() {
  return (
    <>
      <Navigation />
    </>
  );
}

export default App;

该表达式可以引用模型变量、会话属性或请求参数等。

查看位于 https://github.com/jeffbrown/demon101dynamiclayout 的项目。

https://github.com/jeffbrown/demon101dynamiclayout/blob/a383176ccc728a93a05a365638149dde8c548737/grails-app/views/layouts/plain.gsp

<meta name="layout" content="${someVariable}"/>

https://github.com/jeffbrown/demon101dynamiclayout/blob/a383176ccc728a93a05a365638149dde8c548737/grails-app/views/demo/index.gsp

<!doctype html>
<html lang="en" class="no-js">
<head>
    <title>
        <g:layoutTitle default="Grails"/>
    </title>
    <g:layoutHead/>
</head>

<body>

<H1>This Is A Plain Ole Layout</H1>
<g:layoutBody/>

</body>
</html>

https://github.com/jeffbrown/demon101dynamiclayout/blob/a383176ccc728a93a05a365638149dde8c548737/grails-app/controllers/demon101dynamiclayout/DemoController.groovy

<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
    <meta name="layout" content="${dynamicLayout ?: 'main'}">
    <title></title>
</head>

<body>

</body>
</html>
,

通过 grails 代码探索,我发现了 GroovyPageLayoutFinder 类 它有线

final Object layoutAttribute = request.getAttribute(LAYOUT_ATTRIBUTE);

我可以将 org.grails.layout.name 属性放在 Interceptor 中进行请求。它就像一个魅力!