【发布时间】:2020-05-24 06:48:12
【问题描述】:
我喜欢 Pug 的简单性,但有时它的行为不规律,而且很难提炼出问题所在。我正在使用 Node、Express 和 Pug(又名 Jade),我需要将我的 URL(window.local.href)附加到一个字符串中。 我无法让 Pug 访问 window.local.href
我已经阅读了它的插值,在 GitHub 上搜索了 Pug 文件,在 SO 中搜索了这里。仍然无法使其在当前 URL 的 href 属性中显示。 我已经成功地在 y 项目中的几个模板中使用了变量,有时经过几次试验和错误。
但我在这里卡住了。试图蛮力解决这个问题:
script.
currentURL = window.location.href
console.log(currentURL) // Works as expected
console.log(window.location.href) // Works as expected
pre= currentURL // undefined
pre= window.location.href // error because everything is undefined
input.sample(type='button', value="alert href", onclick="alert(window.location.href)") // Works as expected
也经历过(以防万一):
a(href = 'https://url-to-append-it-to.com/?status=!{window.location.href}')
a(href = 'https://url-to-append-it-to.com/?status=#{window.location.href}')
a(href = 'https://url-to-append-it-to.com/?status=${window.location.href}')
a(href = `https://url-to-append-it-to.com/?status=${currentURL}`)
a(href = `https://url-to-append-it-to.com/?status=#{window.location.href}`)
a(href = `https://url-to-append-it-to.com/?status=!{window.location.href}`)
还有(一一):
- currentURL = window.location.href // Cannot read property 'location' of undefined
a(href=${window.location.href}) // Unexpected token
a(href=#{window.location.href}) // Unexpected character '#'
a(href=window.location.href) // Cannot read property 'location' of undefined
a(href=${currentURL}) // Unexpected token
a(href=#{currentURL}) // Unexpected character '#'
a(href=currentURL) // links to undefined
a(href=${window.location.href}) // Unexpected token
我还尝试将window.location.href 附加到locals.currentURL 之类的东西上,但没有成功。
现在,我决定从路由文件中传下来:currentLocation: req.protocol + "://" + req.headers.host + req.url 并按如下方式使用它:
a(href= `https://url-to-append-it-to.com/?status=${currentLocation}`)
这很好用,但我想知道在尝试从 Pug 请求本地浏览器变量时我遗漏了什么。
我假设当 pug 被渲染时脚本标签确实在客户端运行,但也许我遇到问题的变量正在尝试在渲染中运行?我不知道。
【问题讨论】:
-
你能展示一下你是如何渲染哈巴狗的吗?
标签: javascript html express templates pug