Search code examples
node.jsnunjucks

Cannot resolve nunjucks template


Created a simple script to attempt to render a nunjucks template (Both the contact content and layout template are in the src directory:

 let fs = require('fs');
 let nj = require('nunjucks');

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

The contact content looks like this:

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

The layout template looks like this:

  <!DOCTYPE>
  <html>
  <head>
        <title>{{ title }}</title>
  </head>
    <body>
    {% block content %}
    {% endblock %}
    </body>
    </html>

When running the script it throws:

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

Solution

  • I was using the API wrong. Instead of reading in the file and telling Nunjucks to render it do this:

            nj.configure('src');
            let result = nj.render('contact.html');
    

    Bot the contact.html and _template.html files are in the src directory. Almost too easy :)