Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Pug and other template engines

Pug is not the only template engine for Node.js. Its main difference is its own indentation-based syntax. The other popular engines keep plain HTML and add insertions to it. Let's compare them on one task: a list of drinks from the menu array.

One list in four template engines

In Pug, the file src/index.pug:

ul
  each item in menu
    li #{item.name} — $#{item.price}

Pug produces this HTML, and the three variants below give the same list:

<ul>
  <li>Espresso — $2</li>
  <li>Cappuccino — $3</li>
</ul>

EJS — HTML with insertions of plain JavaScript (the Express course uses it):

<ul>
  <% menu.forEach((item) => { %>
    <li><%= item.name %> — $<%= item.price %></li>
  <% }) %>
</ul>

Nunjucks — HTML with {% %} tags for logic and {{ }} for output:

<ul>
  {% for item in menu %}
    <li>{{ item.name }} — ${{ item.price }}</li>
  {% endfor %}
</ul>

Handlebars — HTML with minimal logic: only simple conditions, loops and helpers:

<ul>
  {{#each menu}}
    <li>{{name}} — ${{price}}</li>
  {{/each}}
</ul>

Comparison

PugEJSNunjucksHandlebars
Template baseIts own syntaxHTMLHTMLHTML
LogicJavaScriptJavaScriptIts own languageHelpers
Template inheritanceYesNoYesNo
Mixins or macrosMixinsNoMacrosPartials
Copied ready-made HTMLMust be rewrittenWorks as isWorks as isWorks as is

When to choose Pug

  • You write the markup yourself and value brevity: no closing tags, no way to forget to close a div.
  • You need layouts, includes and mixins, with logic in plain JavaScript rather than a new language.
  • The site is built in advance or served by a Node.js server.

When another one fits better

  • The markup is edited by people who know only HTML, or you often copy ready-made HTML snippets: they would have to be translated into Pug.
  • The project is already built on another engine, such as EJS in the Express course.
  • You need a large ecosystem: Pug evolves slowly — version 3 came out in 2020, and since then only fixes have been released.

How Pug differs from HTML

A plain HTML file knows nothing about data: a list of twenty drinks has to be written by hand, and the header copied to every page. Pug solves both at build time, and the browser still receives ordinary HTML. If the site is a single page with nothing repeated, you do not need a template engine — HTML is enough.

Common mistake

Pasting a chunk of HTML copied from another project into a .pug file. Pug copies lines that start with < as they are, but a line with text alone is a tag to it:

<p>
  Fresh coffee every day.
</p>

Pug reads "Fresh" as a tag name, and the text ends up inside a made-up tag:

<p>
<Fresh>coffee every day.</Fresh></p>

Translate copied markup into Pug completely: p Fresh coffee every day.

Thanks for reading!

Donate to the site — we work hard for you.