Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/385.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript node.js中Jade模板的全局变量_Javascript_Node.js_Templates_Global Variables_Pug - Fatal编程技术网

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