Written by: Geoffrey Callaghan
Nunjucks tutorial
Nunjucks Tutorial
Nunjucks is a powerful templating engine for JavaScript, heavily inspired by Jinja2 and used in various web development frameworks like Express.js and Eleventy. It allows you to create dynamic HTML templates by embedding JavaScript code within your HTML files. Here’s a basic tutorial to get you started with Nunjucks:
You can install Nunjucks via npm:
npm install nunjucks
After installation, you can use Nunjucks in your Node.js project. Here’s a basic setup:
const nunjucks = require('nunjucks');
// Configure Nunjucks to look for templates in a specific directory
nunjucks.configure('views', {
autoescape: true,
express: app // If using Express.js
});
// Render a template
nunjucks.render('index.html', { /* context object */ });
Nunjucks uses double curly braces ({{ }}
) for outputting variables and {% %}
for control statements like loops and conditionals. Here are some examples:
<!-- Output a variable -->
<p>{{ username }}</p>
<!-- Loop through an array -->
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
<!-- Conditional statement -->
{% if isAdmin %}
<p>Welcome, Admin!</p>
{% else %}
<p>Welcome, User!</p>
{% endif %}
Nunjucks supports template inheritance, allowing you to create a base template and extend it in child templates. Here’s an example:
base.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %}My Website{% endblock %}</title>
</head>
<body>
<header>
{% block header %}
<h1>Welcome to My Website</h1>
{% endblock %}
</header>
<main>
{% block content %}
<p>This is the content of the page.</p>
{% endblock %}
</main>
<footer>
{% block footer %}
<p>© 2024 My Website</p>
{% endblock %}
</footer>
</body>
</html>
child.html:
{% extends "base.html" %}
{% block title %}Child Page{% endblock %}
{% block content %}
<p>This is the content of the child page.</p>
{% endblock %}
Nunjucks allows you to define custom filters and functions to manipulate data within your templates. Here’s an example of defining a filter:
const nunjucks = require('nunjucks');
nunjucks.configure({ /* configuration */ });
nunjucks.addFilter('uppercase', function(str) {
return str.toUpperCase();
});
And then you can use it in your templates:
<p>{{ username | uppercase }}</p>
This tutorial covers the basics of Nunjucks templating engine. It’s a versatile tool for creating dynamic web content and can be used in both server-side and client-side applications. Experiment with Nunjucks’ features to discover its full potential in your projects!