【问题标题】:Concatenating a variable + string in Jade file在 Jade 文件中连接变量 + 字符串
【发布时间】:2013-10-23 16:49:06
【问题描述】:

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

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

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

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

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

【问题讨论】:

    标签: html node.js express pug


    【解决方案1】:

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

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

    等效:

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

    何时使用#{}

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

    【讨论】:

      【解决方案2】:

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

      Node.js(从 v4.0.0 开始)支持template literals,所以

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

      等效:

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

      【讨论】:

        猜你喜欢
        • 2021-12-06
        • 1970-01-01
        • 1970-01-01
        • 2015-09-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多