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?
Use pipe of dump
and safe
filters:
<script>
var myObjectName = {{ myObject.name | dump | safe }};
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With