4

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!

Js.
  • 423
  • 3
  • 13

1 Answers1

3

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.

Js.
  • 423
  • 3
  • 13
  • Hello! How did you manage to make metalsmith and nunjucks work together? I've tried both `layouts` and `in-place`, but they are not processing the `.nj` files at all in most configurations I've tried. Could you please share your configuration? Thanks! – Slava Fomin II Nov 18 '17 at 11:51
  • 1
    Make sure to use `.njk` or `.nunjucks` as the extension for Nunjucks. JSTransformer automatically matches the transformers depending on the file extensions. Take a look at [this list](https://github.com/jstransformers/inputformat-to-jstransformer/blob/master/dictionary.json) as a reference. – Js. Dec 04 '17 at 02:55
  • Yeah, thanks. I've figured that out by looking through the source code. I've actually written an article on this subject: https://medium.com/@slavafomin/making-metalsmith-to-work-with-nunjucks-a67a74c3e73d – Slava Fomin II Dec 05 '17 at 20:19