Jade模板布局不能与Node.js结合使用
我正在尝试在使用Jade模板和布局的Node.js中创build一个简单的服务器。 出于某种原因,它只会加载模板而不是布局。
这是我得到的:
main.js
var express = require('express'); var app = express.createServer(); app.set('views', __dirname + '/views'); app.set('view engine','jade'); app.set('view options', { layout: true }); app.get('/', function(req,res) { res.render('index', { title: 'My site' }); }); app.listen(4000);
正如你所看到的布局已启用。 我已经尝试直接在渲染方法中引用它,但它没有区别。 值得注意的也可能是“标题:”我的网站“也不起作用。
index.jade
h2 Hello! p I really hope this is working now
lo.jade
!!! 5 html head title Why won't this work body h1 I AM A LAYOUT div= body
这是我的npm list
:
├─┬ express@3.0.0alpha1 │ ├── commander@0.5.2 │ ├─┬ connect@2.1.2 │ │ ├── crc@0.1.0 │ │ ├── formidable@1.0.9 │ │ ├── mime@1.2.4 │ │ └── qs@0.4.2 │ ├── debug@0.6.0 │ ├── mime@1.2.5 │ └── mkdirp@0.3.1 └─┬ jade@0.24.0 ├── commander@0.5.2 └── mkdirp@0.3.0
任何想法,为什么这是行不通的?
我认为你正在做错误的布局。 我这样做:
我将布局设置为false:
app.set('view options', { layout: false });
在layout.jade文件中:
doctype 5 html(lang="en") head title MySite #{title} body block mainContent
而在渲染的页面(比方说:home.jade),其中包含一个variables(内容)
extends layout block mainContent h1 This is home p= content
你可以有另一个页面基于(扩展)相同的布局(other.jade)与不同的variables(用户)
extends layout block mainContent h1 Oh look ! Another page p= user
并像这样称呼他们:
app.get('/', function(req, res) { res.render('home', { title : "Home", content: "Some Home page content" }); }); app.get('/anotherPage', function(req, res) { res.render('other', { title : "Other page", user: "Here goes a user name" }); });
这似乎是对最新版本的Express / jade的改变。
Express: '3.0.0alpha1': '2012-04-18T22:47:46.812Z' Jade: '0.25.0': '2012-04-18T22:40:01.162Z'
把我也抓出来了!
其他几件事情也发生了变化 – 花了我一些时间来解决这个问题。
不幸的是,Express&Jade没有特别的文档logging,你在网上find的许多例子都是过时的。
Arnaud已经给出了现在使用布局的新方法。 我不知道旧的方法是可行的。 当然,当我尝试像dtyon的东西,似乎不再工作。
因此,使用以下命令检查您安装的Express&Jade版本:
npm show express dist.tarball npm show jade dist.tarball
希望这可以帮助。 J.
据我所知,默认情况下,布局文件应该被命名为“layout.jade”。 但是,如果您需要不同的名称,则可以在呈现时使用“布局”提示选项:
res.render('index', { layout: 'lo', title: 'My site' });
我还假设lo.jade布局文件位于根目录/views/
。
我有同样的问题,只是让人们知道,布局工作在快/玉的新方式是布局已经默认扩展,你的块自动被传递为一个“身体”variables
例如
index.jade
/* This will be passed as "body" no need for "block body" */ h1= title p Welcome to #{title}
layout.jade
doctype html head meta(charset='utf-8') body /* body is output here using != which outputs variable without escaping characters */ section!= body