Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is there anyway to embed native javascript in template? #419

Closed
YoleYu opened this issue Apr 28, 2015 · 2 comments
Closed

Is there anyway to embed native javascript in template? #419

YoleYu opened this issue Apr 28, 2015 · 2 comments

Comments

@YoleYu
Copy link

YoleYu commented Apr 28, 2015

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() }}

@ArmorDarks
Copy link

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:

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

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

  2. Add custom filter as per https://mozilla.github.io/nunjucks/api.html#custom-filters

  3. Add custom global (value or function) — in you case it something that suits better, as per https://mozilla.github.io/nunjucks/api.html#addglobal

  4. 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.

@jlongster
Copy link
Contributor

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 !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants