Html 在 Jade 文件中连接变量 + 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19388733/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 14:29:22  来源:igfitidea点击:

Concatenating a variable + string in Jade file

htmlnode.jsexpresspug

提问by gjw80

I am passing in a session variable from my mongodb session store in an Express for Node.js web app like this:

我正在一个 Express for Node.js web 应用程序中从我的 mongodb 会话存储中传入一个会话变量,如下所示:

exports.dashboard = function(req, res){
    res.render('dashboard', {pref: req.session.layoutpref});
}

Then, in my Jade file I'm trying to assign the value of prefto the css link like this, but I'm getting a syntax error:

然后,在我的 Jade 文件中,我试图将 的值分配给pref这样的 css 链接,但出现语法错误:

head
        title #{title}
        link(rel='stylesheet', href='/stylesheets/' + #{pref} + '.css')

I'm almost certain the problem is in my concatenation of prefinto the location of the css file to be used. Any ideas how to fix this?

我几乎可以肯定问题出在我连接pref到要使用的 css 文件的位置中。任何想法如何解决这一问题?

回答by Plato

use #{}notation if you want to interpolate a variable in the contents of an element. you can just use the variable names straight up if you want to use them in attributes.

#{}如果要在元素的内容中插入变量,请使用符号。如果你想在属性中使用它们,你可以直接使用变量名。

link(rel='stylesheet', href='/stylesheets/' + pref + '.css')

equivalent:

相等的:

link(rel='stylesheet', href='/stylesheets/' + locals.pref + '.css')

when to use #{}:

何时使用#{}

a(href='/stylesheets/' + locals.pref + '.css') View the stylesheet at #{pref}

回答by Vitaly Shapovalov

Jade files are compiled in Node.js env.

Jade 文件在 Node.js 环境中编译。

Node.js (from v4.0.0) supports template literals, so

Node.js(来自 v4.0.0)支持模板文字,所以

link(rel='stylesheet', href=`/stylesheets/${pref}.css`)

equivalent:

相等的:

link(rel='stylesheet', href='/stylesheets/' + pref + '.css')