繁体   English   中英

如何访问 pug 中的 JavaScript 变量值?

[英]How to access a JavaScript variable value in pug?

我的index.pug文件如下所示:

head
    script(type="text/javascript").
        var isMobile = (screen.width || window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth) <= 480;
body
    if isMobile
        include nav_mobile
    else
        include nav

我写了上面的代码,但没有得到想要的结果。 isMobile似乎总是null

如何获取 JavaScript 变量的值以进行 pug?

获取屏幕尺寸的方法不止一种。 具体来说,对于哈巴狗,我建议使用脚本编写一个页面,该脚本获取屏幕大小并重定向到正确的端点或将详细信息添加到会话或 URL 查询中,然后将它们发送到服务器,然后您就可以将它们放在您的路线上并将它们传递给pug 渲染器

同样在未来,我建议使用 CSS 来处理移动/桌面设计,而不是使用 javascript 来处理它。 因为如果您在使用任一版本时更改屏幕大小,它都不会更改设计,您将不得不重新加载页面。

在呈现该视图的请求处理程序中,您必须传递您希望在视图中访问的变量列表

app.get('/', function (req, res) {
    // your code goes here
   // you pass each variable in the second parameter to the render method of response object
    res.render('index', { isMobile: true });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM