使用ejs渲染布局

kar*_*una 0 ejs node.js express

我不能用ejs渲染布局,表达:

app.configure(function () {
    app.use(express.static(__dirname + '/public'));
    app.use(express.basicAuth('username', 'password'));
    app.set('views', __dirname + '/views');
    app.set('view engine', 'ejs');
});
Run Code Online (Sandbox Code Playgroud)

layout.ejs位于/ views文件夹中.我渲染/views/home/index.ejs但它不是布局:

res.render('home/index');
Run Code Online (Sandbox Code Playgroud)

layout.ejs:

<html>
  <head>
    <title></title>
      <script type="text/javascript" src="/content/scripts/jquery-1.6.2.min.js"></script>
      <script type="text/javascript" src="/content/scripts/jquery-ui-1.8.11.min.js"></script>
      <script type="text/javascript" src="/content/scripts/jquery.unobtrusive-ajax.min.js"></script>
      <script type="text/javascript" src="/content/scripts/jquery.validate.min.js"></script>
      <script type="text/javascript" src="/content/scripts/jquery.validate.unobtrusive.min.js"></script>
      <script type="text/javascript" src="/socket.io/socket.io.js"></script>
      <link rel="stylesheet" type="text/css" href="/content/styles/site.css" />
      <link rel="stylesheet" type="text/css" href="/content/styles/themes/base/jquery.ui.all.css"/>
  </head>
  <body>
      <%- body %>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

cho*_*ovy 12

我改用ejs-locals.它是ejs-partials的一个分支,但是积极维护.

npm install ejs-locals
Run Code Online (Sandbox Code Playgroud)

https://github.com/RandomEtc/ejs-locals

<% layout('boilerplate') -%>
<% script('foo.js') -%>
<% stylesheet('foo.css') -%>
<h1>I am the <%=what%> template</h1>
<% block('header', "<p>I'm in the header.</p>") -%>
<% block('footer', "<p>I'm in the footer.</p>") -%>
Run Code Online (Sandbox Code Playgroud)

和布局,boilerplate.ejs:

<!DOCTYPE html>
<html>
  <head>
    <title>It's <%=who%></title>
    <%-scripts%>
    <%-stylesheets%>
  </head>
  <body>
    <header>
      <%-blocks.header%>
    </header>
    <section>
      <%-body -%>
    </section>
    <footer>
      <%-blocks.footer%>
    </footer>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

  • `ejs-locals`现在没有维护!还有其他建议吗? (3认同)
  • 虽然不理想,但这些似乎是最可行的替代品:[ejs-mate](https://www.npmjs.com/package/ejs-mate)和[express-ejs-layouts](https:// www. npmjs.com/package/express-ejs-layouts).ejs-mate是一个分支,具有更多功能,但自2015年8月以来未更新. (2认同)

Pat*_*ick 5

在express 3中,需要用express-partials分别添加partial和layout支持

npm install express-partials
Run Code Online (Sandbox Code Playgroud)