Nunjucks: Is there anyway to embed native javascript in template?

Created on 28 Apr 2015  Â·  2Comments  Â·  Source: mozilla/nunjucks

Nunjucks have a lot build in filters, they do great help to writing templates.

But if we want more flexibility from native javascript language, how to do it with Nunjucks?
EJS and JSP have such feature.

For example, I want to show current date. I can't do it with something like {{ Date.now() }}

Most helpful comment

You always have at least 4 options:

  1. Pass into template custom data (like in that Grunt task https://github.com/vitkarpov/grunt-nunjucks-2-html/blob/master/tasks/nunjucks.js).

You can set in your data something like:

coffee data: currentYear: new Date().getFullYear()

After passing into template call it with {{ currentYear }}

  1. Add custom filter as per https://mozilla.github.io/nunjucks/api.html#custom-filters
  2. Add custom global (value or function) — in you case it something that suits better, as per https://mozilla.github.io/nunjucks/api.html#addglobal
  3. Use native JS methods. Yeap, actually you can use them, but sometimes their usage is a bit limited.

Your example doesn't work, because Data() is JS constructor, not global variable. To call constructor you need to define it with new Date(). new is one of those JS native operators that won't work in Nunjucks templates, thus you won't be able to call constructors right in your templates unless you'll added special filter or global function for it.

In your case you need anyway to map that constructor to filter, global variable or pass it as data.

All 2 comments

You always have at least 4 options:

  1. Pass into template custom data (like in that Grunt task https://github.com/vitkarpov/grunt-nunjucks-2-html/blob/master/tasks/nunjucks.js).

You can set in your data something like:

coffee data: currentYear: new Date().getFullYear()

After passing into template call it with {{ currentYear }}

  1. Add custom filter as per https://mozilla.github.io/nunjucks/api.html#custom-filters
  2. Add custom global (value or function) — in you case it something that suits better, as per https://mozilla.github.io/nunjucks/api.html#addglobal
  3. Use native JS methods. Yeap, actually you can use them, but sometimes their usage is a bit limited.

Your example doesn't work, because Data() is JS constructor, not global variable. To call constructor you need to define it with new Date(). new is one of those JS native operators that won't work in Nunjucks templates, thus you won't be able to call constructors right in your templates unless you'll added special filter or global function for it.

In your case you need anyway to map that constructor to filter, global variable or pass it as data.

If you want that you just need to use EJS. Nunjucks is not JS, even if it looks like a subset sometimes. Thanks for the detailed reply @ArmorDarks !

Was this page helpful?
0 / 5 - 0 ratings