Nunjucks访问窗口屏幕尺寸

时间:2018-07-16 09:59:20

标签: templating nunjucks

是否可以通过Nunjucks获取窗口大小参数? 目前,我正在尝试:

{% if window.screen.width < 800 %}
    {% include 'partials/sort.html' %}
{% endif %}

据我了解,Nunjucks模板无法访问前端参数,但是有什么办法可以解决此问题? (为记录起见,我正在使用nodejs作为服务器端代码)

1 个答案:

答案 0 :(得分:1)

您可以将窗口大小存储在cookie中,并将它们的值传递到呈现器res.render(templ, {cookies})中:如果页面请求中不存在size-cookie,则返回一个“特殊”页面,将窗口大小存储到cookie中并重定向到请求的页面。

以下是这种方式的示例(app.js需要安装expressnunjucks模块):

// app.js
var express = require ('express');
var nunjucks  = require('nunjucks');
var app = express();
var env = nunjucks.configure('.', {autoescape: true, express: app});

function parseCookies(cookies) {
    return cookies && cookies.split(';').reduce(function(res, cookie) {
        var pair = cookie.split('=');
        res[pair.shift().trim()] = decodeURI(pair.join('='));
        return res;
    }, {}) || {};
}

app.get('/set-cookie', function(req, res) {
    res.render('setter.html');
});

app.get('*', function(req, res){
    let cookies = parseCookies(req.headers.cookie) || {};
    if (!cookies.width || !cookies.height)
        return res.redirect('/set-cookie?' + req.url);

    res.render('index.html', {width: cookies.width, height: cookies.height});   
});

app.listen(3000, function() {
    console.log('Example app listening on port 3000...');
});

// index.html
<html>
<body>
{{width}} x {{height}}
</body>
</html>

// setter.html
<html>
<head>
<script type="text/javascript">
    // store window size to cookies and redirect to origin page 
    function setWindowSize () {
        document.cookie = 'width=' + window.innerWidth;
        document.cookie = 'height=' + window.innerHeight;
        location = location.search.substring(1); 
    }
</script>
</head>
<body onload = "setWindowSize()">
</body>
</html>