使用ejs渲染布局

时间:2012-10-21 14:06:54

标签: node.js express ejs

我无法使用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');
});

layout.ejs位于/ views文件夹中。我渲染/views/home/index.ejs但布局中 NOT

res.render('home/index');

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>

2 个答案:

答案 0 :(得分:12)

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

npm install ejs-locals

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>") -%>

布局,样板文件.js:

<!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>

答案 1 :(得分:4)

在快递3中,您需要使用express-partials

分别添加部分和布局支持
npm install express-partials