nunjucksmetalsmith

Using nunjucks includes with Metalsmith-in-place causing rendering error


I'am using Metalsmith with Nunjucks to create a static website.

I have no issue creating a blog-like website, meaning creating a layout in which I could wrap some markdown content, using the metalsmith-layout plugin.

But I would like to create some views that :

For instance, an index.njk :

{% extends "layouts/base.njk" %}

{% block content %}

Hello World!

{% include components/test1.njk %}

{% include components/test2.njk %}

{% include components/test3.njk %}

{% endblock %}

I tried to use the metalsmisth-in-place plugin with :

.use(inplace({
    engineOptions: {
        path: __dirname + '/src/templating'
    }
})

but I have a an error : The Transform "nunjucks" does not support rendering synchronously

It seems that inplace() cannot render the include properly...

Any idea ?


Solution

  • Ok, I had some great answer and explanation on the metalsmith slack.

    First, the folder structure should be something like:

    layouts/
        base.njk
    components/
        test.njk
    partials/
        head.njk
    src/
        index.njk
    

    The reason is that the src folder should only gather the main content, all the nunjucks files are only adding to this content.

    Then, with this configuration, a simple .use(inplace()) is enough. A directory option could be added if the directory is different from ./layouts.

    With this set up, this index.njk works fine:

    {% extends "./layouts/base.njk" %}
    
    {% block content %}
    
    Hello World!
    {% include './components/test.njk' %}
    
    {% endblock %}
    

    With a base.njk layout being:

    <!doctype html>
    <html class="" lang="">
    
      {% include '../partials/head.njk' %}
    
      <body>
    
        {% block content %}{% endblock %}
    
      </body>
    
    </html>
    

    Be careful however, as I have been told:

    Hope I explain it and understood it well^^

    Thanks a lot to "ismay" for taking some times to help me on the Metalsmith slack.