When shortcodes and code examples collide in Eleventy with Nunjucks

In my articles i sometimes use code examples like this one: {{.Prev}}. It's a template variable, in this case from the static site generator Hugo.

The problem

When moving my blog over to Eleventy with Nunjucks templating, i suddenly had the problem that some of my articles couldn't be rendered anymore. The templates are written in Nunjucks, the articles are written in markdown.

The reason is, Nunjucks would go ahead and also try processing those code snippets in the markdown files. If a thing starts with a curly brace, it's Nunjucks' time to shine.

Why does it do that? Shortcodes.

With eleventy i'm now using this image shortcode {% image "./src/", "your alt text", "classname" %}.

The options

One place to step in, could be the markdown parsing. In the Eleventy config file, you can set the markdownTemplateEngine. At some point, i found the recommendation to set markdownTemplateEngine: false or markdownTemplateEngine: md. This is fine until you want to use shortcodes.

Now i could add images using the HTML tag <img>. But do i really want to prepare 2 or more image sizes every time i add an image in one of my articles? Certainly not.

I did want to keep Nunjucks in my markdown process. The Eleventy image package is really useful.

At some point i read about escaping things with a backslash \ before the character in question. Rendering works, but Nunjucks simply prints this out: \{\{\.Prev}}

I found my solution within this Github issue Template Render Error with Markdown file using Nunjucks engine: the raw tag: { % raw %}.

The My solution

Part 1: the template engine

Since i'm only using Nunjucks for my template and shortcodes, i set this as my markdown template engine.

module.exports = function (eleventyConfig) {
  // all the configs

  return {
    // other return values
    markdownTemplateEngine: "njk"
  }
}

Part 2: the raw tag

In order to get Nunjucks process the image shortcode while not processing the Variables in the code snippets, i use the raw tag around code examples in question.

When writing in markdown, it will look like this:

Here's a code example: {%raw%}`{{.Prev}}`{%endraw%}

This is also necessary for code blocks when they show template variables.

In the case of my article about previous and next links, where i have these code examples sprinkled all over the place, i simply added the tags around the whole article.