Search code examples
node.jsexpressnunjucks

Accessing Express.js local variables in client side JavaScript (nunjucks)


This is bascially the same as this question, except that I am using nunjucks as a template engine.

I am passing a variable to a nunjucks template using express's render method:

res.render('template.html', {myObject:myObject})

I want to access it in my client-side javascript. So far, the only way I have figured out is to put it in an invisible HTML element and pull it into the javascript from there:

<span id='local-variable' style="display:none">{{ myObject.name }}</span>

<script>
    var myObjectName = $('#local-variable').text();
</script>

Is there a better method?


Solution

  • Use pipe of dump and safe filters:

    <script>
        var myObjectName = {{ myObject.name | dump | safe }};
    </script>