ki9
ki9

Reputation: 5575

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?

Upvotes: 5

Views: 2987

Answers (1)

stdob--
stdob--

Reputation: 29172

Use pipe of dump and safe filters:

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

Upvotes: 12

Related Questions