Node.js中Jade模板的全局变量

5

我正在使用 node.jsJade 模板系统。

假设,我有以下路由规则:

// ./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变量,使其适用于所有视图?


Express.js 视图全局变量的副本:https://dev59.com/J2445IYBdhLWcg3wustT - Jan Jůna
1个回答

2
// ./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'
    });
};

或者

// ./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

谢谢你的回答,我一直在使用继承模板,就像你在第二个变体中提出的那样。只是想知道是否有更简单的方法。目前还没有找到更好的解决方案。 :) 第一个示例只会让事情变得更加复杂。 - Edward Ruchevits
使用 app.locals.author = "Jeffry" 代替在每个地方重复你的代码,这样你就可以遵循 DRY 原则(https://en.wikipedia.org/wiki/Don't_repeat_yourself)。 - Jan Jůna
@JanJůna,不要使用全局状态,这样你就可以轻松地测试和支持你的代码了(https://en.wikipedia.org/wiki/Global_variable#Use)。 - penartur

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接