Table of Contents

Nunjucks Tricks

Syntax highlighting in VS Code~editors

This is a modern fork of the original extension. It is specifically designed to solve the "11ty problem" where you mix Nunjucks and HTML.

Why it's better: It injects Nunjucks grammar directly into the standard HTML grammar. This means you get full Nunjucks highlighting and the editor still knows it's an HTML file, giving you better Emmet and CSS autocompletion.

No Config: It works out of the box without needing to manually map file associations in your settings.

Auto-formatting in VS Code~editors

  1. 🧩 Install /prettier/prettier-vscode (if not yet)

  2. Install a compatible Prettier plugin for your project, for example:

npm i -D prettier-plugin-jinja-template
  1. It might be tricky to find a well-maintained Nunjucks plugin, but jinja-template works just fine with .njk via .html override:
{
  "plugins": ["prettier-plugin-jinja-template"],
  "overrides": [
    {
      "files": ["*.njk", "*.html"],
      "options": {
        "parser": "jinja-template"
      }
    }
  ]
}

PRO TIP: If you already use /anydigital/bricks, it’s even easier. You can simply:

ln -s ./node_modules/@anydigital/bricks/.prettierrc.json

Sort array by attribute

Per official .njk documentation:

sort(arr, reverse, caseSens, attr)
Sort arr with JavaScript's arr.sort function. If reverse is true, result will be reversed. Sort is case-insensitive by default, but setting caseSens to true makes it case-sensitive. If attr is passed, will compare attr from each item.

But you can actually do this trick:

{% for item in array | sort(attribute='weight') %}
  ...
{% endfor %}

Include and render .md file w/o its Front Matter in 11ty

{# first, get the raw content using `html` as plain-text engine #}
{% set _eval = "{% renderFile './YOUR_FILE.md', {}, 'html' %}" %}
{% set _raw_md = _eval | renderContent('njk') %}

{# then, remove the front matter using regex, and render using `md` #}
{{ _raw_md | replace(r/^---[\s\S]*?---/, '') | renderContent('md') | safe }}