4

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?

Community
  • 1
  • 1
ki9
  • 5,183
  • 5
  • 37
  • 48

1 Answers1

9

Use pipe of dump and safe filters:

<script>
    var myObjectName = {{ myObject.name | dump | safe }};
</script>
stdob--
  • 28,222
  • 5
  • 58
  • 73