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

Error expected variable end #650

Closed
Paxa opened this issue Jan 27, 2016 · 2 comments
Closed

Error expected variable end #650

Paxa opened this issue Jan 27, 2016 · 2 comments

Comments

@Paxa
Copy link

Paxa commented Jan 27, 2016

I'm trying to call some function inside {{ }} and it gives error.

I was trying to print current year:

{{ new Date().getFullYear() }}

How to do it right?

@carljm
Copy link
Contributor

carljm commented Jan 27, 2016

You can call functions, but you can't run arbitrary JS code (so no new), and you can't access arbitrary JS globals, only values you explicitly pass into the template context (so no Date unless you pass it in yourself). You can pass new Date() explicitly into the template context when rendering; if you give it the name now (just as an example) you could then do {{ now.getFullYear() }} in the template.

@ganlanyuan
Copy link

ganlanyuan commented Jan 18, 2017

I use Gulp with Nunjucks. My solution is appending the year value to the data passing to the context.

var data = require('./templates/data.json');
data.year = new Date().getFullYear();

gulp.task('nunjucks', () =>
  gulp.src('templates/*.njk')
    .pipe(nunjucks.compile(data), options)
    .pipe(rename(function (path) {
      path.extname = ".html";
    }))
    .pipe(gulp.dest(''))
);

Then in the layout.njk file I can directly use the year value

<div class="copyright">&copy; {{ year }}</div>

Output in the index.html file

<div class="copyright">&copy; 2017</div>

newbienewbie pushed a commit to newbienewbie/skeleton that referenced this issue Jul 18, 2017
You can call functions, but you can't run arbitrary JS code (so no new), and you can't access arbitrary JS globals, only values you explicitly pass into the template context (so no Date unless you pass it in yourself).

mozilla/nunjucks#650 (comment)
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