是否可以将多个<% - %>语句添加到node.js ejs布局中

Osc*_*hed 5 ejs node.js

我刚刚开始使用node.js,express和ejs.而且我在layout.ejs文件上遇到了困难.我想要做的是类似于你在.net中可以做的事情,你有多个内容占位符,在视图中你可以有多个块进入不同的占位符.

像这样的东西:

<!DOCTYPE html>
<html>
    <head>
         <title><%- title %></title>
    </head>
    <body>
        <%- body %>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

我的观点应该如何?

Oli*_*let 6

对于给定的布局文件,您可以编写包含以下内容的my_body.ejs文件:

<% title = 'My Page – My Site' %>
<p>The body content could go there</p>    
Run Code Online (Sandbox Code Playgroud)

这将呈现:

<!DOCTYPE html>
<html>
    <head>
         <title>My Page – My Site</title>
    </head>
    <body>
         <p>The body content could go there</p>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

对于更复杂的标题,您还可以使用部分:

my_body.ejs:

<% header = partial('_header.ejs') %>
<p>The body content could go there</p>
Run Code Online (Sandbox Code Playgroud)

_header.ejs:

<h1>My Page Title</h1>
Run Code Online (Sandbox Code Playgroud)

layout.ejs:

<!DOCTYPE html>
<html>
    <head>
         <title>My Page – My Site</title>
    </head>
    <body>
         <div id="header"><%- header %></div>
         <div id="content"><%- body %></div>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)