问题描述
我试图在Node.js中创建一个使用Jade模板和布局的简单服务器。
由于某种原因,它只会加载模板而不是布局。
I'm trying to create a simple server in Node.js which uses Jade templates and layouts.For some reason it will only load the template and not the layout.
这是我所得到的:
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);
正如您可以看到布局已启用。我已经尝试直接在render方法中引用它,但它没有什么不同。值得注意的是,标题:我的网站也不起作用。
As you can see layouts are enabled. I've tried referencing it directly in the render method but it doesn't make a difference. Worth noting might also be that the "title: 'My site'" doesn't work either.
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列表
:
├─┬ [email protected]
│ ├── [email protected]
│ ├─┬ [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ ├── [email protected]
│ │ └── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ └── [email protected]
└─┬ [email protected]
├── [email protected]
└── [email protected]
任何想法,为什么这不工作?
Any ideas on why this isn't working?
推荐答案
我想你在做布局错误的方法。我这样做:
I think you're doing layout the wrong way. I do it this way :
我将布局设置为false:
I set layout to false :
app.set('view options', {
layout: false
});
在layout.jade文件中:
In a layout.jade file :
doctype 5
html(lang="en")
head
title MySite #{title}
body
block mainContent
在渲染页面(让我们说:home.jade),其中包含一个变量(content)
And in the rendered page (let's say : home.jade), which include a variable (content)
extends layout
block mainContent
h1 This is home
p= content
您可以根据(扩展)具有不同变量的相同布局(other.jade) (用户)
You could have another page based on (extending) the same layout (other.jade) with different variables (user)
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"
});
});
这篇关于Jade模板布局不能与Node.js结合使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!