Javascript node.js中Jade模板的全局变量
我正在使用Javascript node.js中Jade模板的全局变量,javascript,node.js,templates,global-variables,pug,Javascript,Node.js,Templates,Global Variables,Pug,我正在使用node.js和Jade模板系统 假设我有以下路由规则: // ./routes/first.js exports.first = function(req, res) { res.render('first', { author: 'Edward', title: 'First page' }); }; // ./routes/second.js exports.second = function(req, res) {
node.js
和Jade
模板系统
假设我有以下路由规则:
// ./routes/first.js
exports.first = function(req, res)
{
res.render('first', {
author: 'Edward',
title: 'First page'
});
};
// ./routes/second.js
exports.second = function(req, res)
{
res.render('second', {
author: 'Edward',
title: 'Second page'
});
};
这些虚拟视图:
// ./views/first.jade
html
head
title #{author} – #{title}
body
span First page content
// ./views/second.jade
html
head
title #{author} – #{title}
body
span Second page content
对于这两个视图,我通常如何声明author
变量
// ./author.js
module.exports = 'Edward';
// ./routes/first.js
exports.first = function(req, res)
{
res.render('first', {
author: require('../author'),
title: 'First page'
});
};
// ./routes/second.js
exports.second = function(req, res)
{
res.render('second', {
author: require('../author'),
title: 'Second page'
});
};
或
或
感谢您的回答,正如您在第二个变体中建议的那样,我一直在使用继承的模板。只是想知道,是否有可能让它变得更容易。还没有找到更好的。:)第一个示例很复杂。请使用
app.locals.author=“Jeffry”
,这样您就不必到处重复代码(DRY-)@JanJůna,不要使用全局状态,这样您就可以轻松地测试和支持您的代码()
// ./views/includes/head.jade
head
title Edward – #{title}
// ./views/first.jade
html
include includes/head
body
span First page content
// ./views/second.jade
html
include includes/head
body
span Second page content
// ./views/layout.jade
html
head
title Edward – #{title}
body
block body
// ./views/first.jade
extends layout
append body
span First page content
// ./views/second.jade
extends layout
append body
span Second page content