简体   繁体   English

在Express 3.x中使用布局

[英]Using Layouts with Express 3.x

All of the guides I've found seem to refer to earlier versions of Express and it's my understanding that this functionality has changed somewhat from 2.x to 3.x. 我发现的所有指南似乎都指向Express的早期版本,据我了解,此功能已从2.x更改为3.x。 I'm assuming that since npm install express currently installs version 3.0.3 that 3.x is considered stable and ready for production use. 我假设自从npm install express当前安装版本3.0.3以来,3.x被认为是稳定的并且可以用于生产。 (Is that not the case?) (不是吗?)

I'd like to use EJS or Kiwi templates, and if possible I'd like to have Underscore available from within templates. 我想使用EJS或Kiwi模板,如果可能的话,我想在模板中使用Underscore。

But my first hurdle is getting a layout to render around my content/partial. 但是我的第一个障碍是获取一种布局以围绕我的内容/部分进行渲染。

Given: 鉴于:

$ express --ejs test

index.js: index.js:

exports.index = function(req, res){
  res.render('index', { title: 'test' });
};

I've created layout.ejs, but I can see when I view source that it's not being called. 我已经创建了layout.ejs,但是当我查看源代码时可以看到它没有被调用。

Have layouts been completely passed off to the template library to deal with in Express 3.x (thus if the template library of choice doesn't implement them, you're SOL)? 布局是否已完全传递给模板库以在Express 3.x中处理(因此,如果选择的模板库未实现布局,则您是SOL)?

If it's still part of Express, how do I configure it? 如果它仍是Express的一部分,如何配置它? If it must be implemented by the templating library, I don't see instructions for layouts in either the EJS or Kiwi documentation -- does that mean they're not supported at all? 如果必须由模板库实现,那么在EJS或Kiwi文档中都看不到布局说明,这是否根本就不支持它们?

Use ejs-locals to get layout support (also provides blocks and partials)...as layouts have been removed in express 3.x. 使用ejs-locals获得布局支持(还提供块和部分)...因为在express 3.x中已删除了布局。

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

Run node app.js from examples and open localhost:3000 to see a working example. 从示例中运行节点app.js并打开localhost:3000以查看工作示例。

Given a template, index.ejs: 给定一个模板index.ejs:

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

And a layout, boilerplate.ejs: 还有一个布局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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM