【问题标题】:How to interpolate a variable into an attribute?如何将变量插入到属性中?
【发布时间】:2019-04-02 04:16:05
【问题描述】:

我需要根据变量 userAccount.image 显示正确的图像,该变量是一个包含图像名称的字符串(即“profile1.png”)。我似乎无法弄清楚在 pug 中将变量传递给属性的语法。

我查看了 pug 的文档,我相信我复制了最接近我的案例的示例,但没有运气。

script.
    var image = '#{userAccount.image}'
img(src="/images/" + image)

控制台抛出如下错误

GET http://localhost:3000/images/ 404 (Not Found)

表示变量image 是一个空字符串。但是,当我在脚本中使用 console.log(image) 时,它会显示“profile1.png”

【问题讨论】:

  • 尽管我找到了解决办法,但我仍然感兴趣是否有办法在不编写 js 脚本的情况下做到这一点。

标签: html pug


【解决方案1】:

我想出了一个办法。

img(id="img")
    script.
        var imgTag = document.getElementById("img")
        var image = '#{userAccount.image}'
        imgTag.setAttribute('src', "/images/" + image)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-29
    • 2019-11-02
    • 2012-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多