Search code examples
markdownnunjucksmetalsmith

How to use Nunjucks' partials / macros / includes with metalsmith-in-place?


I'm having trouble reusing template code within my markdown files. For example I'd like to pull in the embed code for vimeo links and just pass the vimeo id to the call.

One example macro:

{% macro vimeoEmbed(id) %}
  <iframe src="https://player.vimeo.com/video/{{ id }}?title=0&byline=0&portrait=0" width="300" height="169" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
{% endmacro %}

To be used like this:

{{ vimeoEmbed(120394634) }}

This works if I define the macro in the markdown file directly. But of course I'd like to have a global file with the macro for easier maintenance.

I tried to use Nunjucks' {% import "macros.njk" as macros %}. macros.njk would contain the vimeoEmbed macro.
But unfortunately I keep getting Error: template names must be a string: undefined.

As an alternative I tried using {% include "vimeoEmbed.njk" %} but I'm getting the same Error: template names must be a string: undefined.


This seems to be specific to metalsmith-in-place as Nujucks' include and import work just fine with metalsmith-layouts.

Any other solution to reusing code within markdown files and Nunjucks is welcome too. Thanks!


Solution

  • I figured it out myself.

    My mistake was basically to run metalsmith-in-place after the metalsmith-markdown plugin. The Markdown plugin had already converted the quotation marks for example in {{ "some string" }} to {{ &quot;some string&quot; }}. I switch this so in-place is running before Markdown.

    In the meantime I also updated metalsmith-in-place to 2.0.0-beta.1. It now relies on JSTransformer and not consolidate.js anymore. Since the Nunjucks transformer seems to have an issue with Nujucks includes and imports I also had to switch from Nunjucks macros to filters. So I'm not entirely sure this would solve the initial problem, but it's likely.