Nunjucks Templating Language

We will cover the very basics of Nunjucks that you would require while building a theme. You can view the complete official docs of Nunjucks here -https://mozilla.github.io/nunjucks/.

1. Variables

Variables are like containers that store information. In Nunjucks, you can use double curly braces {{ }} to display the content of a variable.

For example

<!-- Suppose product_name = "Cookie" -->

<p>Add to bag, one {{ product_name }}!</p>

This will display: Add to bag, one Cookie!

2. Operators

Operators are symbols that help perform operations on variables, like simple math or comparisons.

For example

<!-- Suppose price = 10 and tax = 2 -->

<p>Total cart cost: {{ price + tax }}</p>

This will display: Total cart cost: 12

3. Loops

Loops are a way to repeat actions or display a list of items. In Nunjucks, you can use the for loop to go through a list and perform an action for each item.

For example:

<!-- Suppose products = ["Bag", "Pen", "Paper"] -->

{% for product in products %}
  <p>{{ product }}</p>
{% endfor %}

This will display:

Bag
Pen
Paper

4. Conditional statements

Conditional statements, like if, elif, and else, allow you to perform different actions based on certain conditions.

For example:

You can display a message depending on whether a user is logged in or not:

<!-- Suppose user_is_logged_in = True -->
<!-- And suppose username = "Kaushik" -->

{% if user_is_logged_in %}
  Welcome, {{ username }}!
{% else %}
  Please log in.
{% endif %}

This will display:

Welcome, Kaushik

5. Template Inheritance

Template inheritance in Nunjucks helps you create a consistent structure for your website by allowing you to reuse a base template and customize specific parts for different pages. It's like having a blueprint that you can use to build various rooms in a house (If you remember the Menu example we explained in the previous chapter). Let's understand with a simple example.

  1. Base Template - layout.html It that has the common structure and elements for your website. Use the {% block %} tag to mark areas that can be customized in child templates.

<!-- layout.html -->
<!DOCTYPE html>
<html>
<head>
  <title>
    {% block title %}
      Default Title
    {% endblock %}
  </title>
</head>
<body>
  <header>
    {% block header %}
      Header
    {% endblock %}
  </header>

  <main>
    {% block content %}
    {% endblock %}
  </main>

  <footer>
    {% block footer %}
      Footer
    {% endblock %}
  </footer>
</body>
</html>
  1. Child Template - product-details.html Create a child template (e.g., product-details.html) that extends the base template using the {% extends %} tag. Then, use the {% block %} tag again to override and customize the content in specific areas.

<!-- product-details.html -->
{% extends "base.html" %}

{% block title %}
  Product Details - My E-commerce Website
{% endblock %}

{% block header %}
  <nav>
    <a href="/">Home</a>
    <a href="/products">Products</a>
    <a href="/about">About</a>
    <a href="/contact">Contact</a>
  </nav>
{% endblock %}

{% block content %}
  <h1>Product Name</h1>
  <img src="/images/product-image.jpg" alt="Product Image" width="300">
  <p>Product description goes here. This product is perfect for those who are looking for a high-quality, stylish, and durable item.</p>

  <h2>Product Details</h2>
  <ul>
    <li>Price: $99.99</li>
    <li>Color: Black</li>
    <li>Size: Medium</li>
  </ul>

  <button>Add to Cart</button>
{% endblock %}

{% block footer %}
  <p>Copyright &copy; 2023 - My E-commerce Website. All rights reserved.</p>
{% endblock %}

6. Include

Include allows you to insert reusable components or partial templates into your main templates. It's like using puzzle pieces to build a complete picture. This feature helps you maintain a consistent structure across your website and avoid repeating code. Here's an example.

Header & footer usually have same content across pages, say product details page, homepage and checkout page. So, it doesn't make sense to duplicate them everywhere, instead we can just define them in 1 file and then use that across all the pages. Let's create 2 files, header.html & footer.html

<!-- header.html -->
<nav>
  <a href="/">Home</a>
  <a href="/products">Products</a>
  <a href="/about">About</a>
  <a href="/contact">Contact</a>
</nav>
<!-- footer.html -->
<p>Copyright &copy; 2023 - My Website. All rights reserved.</p>

Now you can just use these files across all your pages. Let's see how.

<!-- product-details.html -->
{% extends "layout.html" %}

{% block header %}
  {% include "header.html" %}
{% endblock %}

{% block content %}
  <!-- Product details content goes here -->
{% endblock %}

{% block footer %}
  {% include "footer.html" %}
{% endblock %}

Similarly we can also use it in about.html

<!-- about.html -->
{% extends "layout.html" %}

{% block title %}
  About Us - My Website
{% endblock %}

{% block header %}
  {% include "header.html" %}
{% endblock %}

{% block content %}
  <h1>About Us</h1>
  <p>
    Welcome to our website! We are a company dedicated to providing the best
    products and services to our customers. Our team is passionate about
    innovation, and we work hard to ensure that we exceed your expectations.
  </p>

  <h2>Our Mission</h2>
  <p>
    Our mission is to deliver top-quality products and services that make a
    positive impact on people's lives. We strive to achieve this goal by
    constantly improving our processes, staying up-to-date with industry trends,
    and listening to our customers' feedback.
  </p>
{% endblock %}

{% block footer %}
  {% include "footer.html" %}
{% endblock %}

7. Filters

These are used to modify the output of variables or expressions before they are displayed. Think of them as tools that can tweak or transform data into the desired format. Filters are applied using the pipe symbol |. It can be used in the following way.

To convert a text to uppercase we can write this

<!-- Suppose pageTitle = "welcome" -->
{{ pageTitle | upper }}

This will display WELCOME

8. Comments

Comments are used to add notes or explanations to your code that will be ignored by the template engine and will not be displayed on the rendered page.

You can add a comment in Nunjucks by using {# ... #}. Any text within the opening and closing braces will be treated as a comment and ignored by the engine.

For example, in the code below, line 2 is a comment. Note how it starts and ends with a #.

<button class="without-cart-add-to-bag-button btn-outline-primary btn-lg">
          {# Add to bag #}
          {{ DUKAAN_LANGUAGE.ADD_TO_BAG }}
</button>

Conclusion

With this our introduction to Nunjucks is complete and you're all set 🚀, this sums up the bare minimum Nunjucks needed for editing a Dukaan theme. If you want to delve deep into the official documentation here is the link.

Last updated