【问题标题】:How to get multiple content areas in hapi.js ejs layouts?如何在 hapi.js ejs 布局中获取多个内容区域?
【发布时间】:2017-05-17 01:48:33
【问题描述】:

我想在 hapi.js 中使用 ejs 在包含布局中呈现的模板中定义信息。例如:

layout.html

<html>
    <head>
        <title><%- contentFor('title') %></title>
    </head>
    <body>
        <%- content %>
    </body>
</html>

index.html

contentFor('title', 'My title')

<h1>My content</h1>

对我来说重要的是,无论它如何工作,不同的布局内容都是在模板中定义的,而不是在路由级别传递的。这可能吗?

【问题讨论】:

    标签: node.js ejs hapijs hapijs-vision


    【解决方案1】:

    是的,这一点都不明显。我能够做到这一点:

    1. 设置默认上下文对象
    2. 在模板中修改该对象
    3. 在布局中引用该对象的属性

    例如:

    设置默认上下文对象

    server.register(plugins, (err) => {
        ...
        server.views({
            context: {
                layoutContent: {}
            }
        })
    }
    

    修改模板中的对象

    // templates/my_template.html
    <%
        layoutContent = {
            title: 'My Title'
            meta: '<meta name="description" content="my content">'
        }
    %>
    

    在布局中引用对象

    // layouts/layout.html
    <html>
        <head>
            <title><%- layoutContent.title %></title>
            <%- layoutContent.meta %>
        </head>
        <body>
            <%- content %>
        </body>
    </html>
    

    如您所见,您可以将文本或整个标签传递给布局。希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-08
      相关资源
      最近更新 更多