Search code examples
templatingnunjucks

Nunjucks access window screen size


Is there a way to get window size parameters with Nunjucks? Currently I am trying:

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

As I understand, Nunjucks templating does not have access to front-end parameters, but is there any way to go around this? (for the record, i am using nodejs for server-side code)


Solution

  • You can store a window size in cookies and pass them values into a render res.render(templ, {cookies}): if size-cookies don't exists on a page request then return a "special" page where you store window size to cookies and redirect to the requested page.

    Here example of this way (app.js requires installed express and nunjucks modules):

    // 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>