简体   繁体   中英

Importing a Nunjucks Macro?

I have a script that renders a nunjucks contact.html template that looks like this:

    let fs = require('fs');
    let nj = require('nunjucks');
    var contact = fs.readFileSync('./src/contact.html','utf8');
    nj.configure('src');
    let result = nj.render('contact.html');
    console.log(result);

It works fine and logs the correct result .

I'm trying to add a macro now and I put the definition in a templates/forms.njk file. I then try to load it from contacts.html like this:

{% import "templates/forms.njk" as forms %}

{% set title = 'Contact' %}
{% extends '_layout.html' %}
{% block content %}
<h1>Test Template</h1>
{% endblock %}

Now results logs as null , but if I remove the macro import will will log the rendered contact template. Thoughts?

The src directory layout looks like this:

├── contact.html
├── index.html
├── _layout.html
└── templates
    └── forms.njk

The second macro was missing a closing statement {% endmacro %} . Sample project here if anyone wants to play with the setup .

Note also updated the nj.render call to log the error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM