首页 > 解决方案 > 如何使窗口对象对 Pug 可用?

问题描述

我喜欢 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 时脚本标签确实在客户端运行,但也许我遇到问题的变量正在尝试在渲染中运行?我不知道。

标签: javascripthtmlexpresstemplatespug

解决方案


Pug 模板编译(因此插值)不在 DOM 范围内执行,因此它不知道“窗口”、“文档”和“位置”是什么。将此与您的脚本标记的内容进行对比,该标记由浏览器执行,而不是由节点执行。幸运的是,请求对象也有你想要的信息,我们可以将它传递给 Pug。

假设您使用的是 Express Router,当您调用渲染时,您可以传递如下参数:

router.get('/', (req, res) => {
    res.render('/', { currentURL: req.url });
});

请求对象上的其他选项包括 req.originalUrl、req.baseUrl、req.route.path 和 req.query(它是根据查询字符串参数自动构建的对象)。


推荐阅读