Nunjucks Settings for VS Code
Nunjucks?
Nunjucks is a templating language for JavaScript. One of its use-case is to template HTML files. The following is an example from its official docs.
var items = [{ title: “foo”, id: 1 }, { title: “bar”, id: 2}];
<h1>Posts</h1>
<ul>
{% for item in items %}
<li>{{ item.title }}</li>
{% else %}
<li>This would display if the 'item' collection were empty</li>
{% endfor %}
</ul>
Visual Studio Code!
To effectively edit Nunjucks file(.njk) in VS Code, mulitple extensions are needed. Nunjucks support is not built into VS Code, unlike HTML.
Syntax Highlight
Highlights Nunjucks Code for Better Readability
Notice how the following code is color-coded. (e.g. for, else, endfor)
{% for item in items %}
<li>{{ item.title }}</li>
{% else %}
<li>This would display if the ‘item’ collection were empty</li>
{% endfor %}
The extension can be downloaded from here.
Name: Nunjucks
Id: ronnidc.nunjucks
Description: A Nunjucks syntax definition + snippets
Version: 0.3.0
Publisher: ronnidc
Formatter
Formats Nunjucks Code for Better Readability
Notice how the following code is formatted with proper indentation.
{% for item in items %}
<li>{{ item.title }}</li>
{% else %}
<li>This would display if the ‘item’ collection were empty</li>
{% endfor %}
The extension can be downloaded from here.
Name: Nunjucks Template Formatter
Id: okitavera.vscode-nunjucks-formatter
Description: Formatter for Nunjucks template
Version: 0.1.3
Publisher: Nanda Okitavera
The above extension allows frontmatter in-front of nunjucks file.
---
items
- title: foo
id: 1
- title: bar
id: 2
---
Emmet (IntelliSense)
Auto-Completes HTML Tags (with Close Tags)
No extension is needed. Instead, Include HTML Emmeting in njk
and nunjucks
files by modifying VS Code settings on a Project.
@ PROJECT_FOLDER/.vscode/settings.json{
"html.suggest.html5": true,
"emmet.includeLanguages": {
"njk": "html",
"nunjucks": "html"
}
}