Templating In the context of static sites

Templating In the context of static sites

But mostly in the context of Publii, since I use it.

Templating allows you to insert one element (or block) into another to build more complex pages from individual components.

On static websites, templating is often done using template engines that allow you to insert data and reuse components. Here are a few popular technologies for this:

1. Handlebars (HBS)

Publii uses Handlebars for templating. It’s a powerful and easy-to-use templating engine that lets you insert data into templates and dynamically generate pages from that data. With Handlebars, you can:

  • Insert variables.
  • Organize templates logically using constructs like if, each (for loops), etc.
  • Insert partial templates that can be reused throughout the site.

Example of using Handlebars in Publii:

{{> header }} <!-- inserting a partial template -->
<h1>{{title}}</h1> <!-- inserting a variable -->

2. Nunjucks

Nunjucks is another powerful templating engine commonly used on static sites. It allows you to not only insert elements into others but also use more complex constructs such as filters, conditions, loops, etc.

Example:

{% include "header.html" %} <!-- including another template -->
<h1>{{ page.title }}</h1> <!-- rendering a variable -->

3. Liquid

Liquid is another popular templating engine, used in systems like Jekyll. It allows you to insert data into templates and compose pages from various parts.

Example:

{% include header.html %} <!-- inserting a component -->
<h1>{{ page.title }}</h1> <!-- rendering a variable -->

How does this work on a static site?

  1. Partial templates allow you to insert one template into another. For example, if you have a common header or footer, you can create a separate file for them and include it in other pages on the site.

  2. Content data (like page titles, meta tags, tags, etc.) is inserted into templates via variables.

  3. Loops and conditions allow you to dynamically render elements, such as generating a list of posts or displaying pages based on conditions.

In Publii, this looks like:

  • Partial templates for headers, footers, and other components.
  • A block system to insert information into main templates.
  • In Publii, you write data (e.g., page titles and post content) in Markdown or JSON format, and this data is inserted into templates.

Example using Handlebars:

<!-- File header.hbs -->
<header>
  <h1>{{siteTitle}}</h1>
  <nav>{{#each pages}}<a href="{{url}}">{{title}}</a>{{/each}}</nav>
</header>

<!-- File index.hbs -->
{{> header }}  <!-- Inserting header -->
<main>
  <h1>{{pageTitle}}</h1>
  <p>{{pageContent}}</p>
</main>

If you integrate search or add other dynamic elements, using templating allows you to flexibly embed the data you need in any part of the page.