Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 671
Keith Avatar asked Jan 07 '23 14:01

Keith


1 Answers

Use pipe of dump and safe filters:

<script>
    var myObjectName = {{ myObject.name | dump | safe }};
</script>
like image 132
stdob-- Avatar answered Feb 07 '23 18:02

stdob--