Templates

Keeping your HTML clean with templates

Required skills: HTML JSON Javascript

Use this when you want to repeat the same HTML structure multiple times on a page.

There's many times when you want to use the same HTML with different peices of content. For example:

  • A list of links
  • Site navigation
  • An image gallery

All of these would use the same HTML but have different content. But as the content grows, it can make your HTML pages large and hard to edit over time. This is a perfect opportunity to use Wunderbucket templates. Wunderbucket templates allow you to store your content in JSON and format that content in HTML.

You should be familiar with how to create a JSON file and you'll need to use the data-merge-repeat attribute.

/link-list.json

{
  "links": [
    {
      "title": "Wunderbucket",
      "url": "https://wunderbucket.io"
    },
    {
      "title": "Smmall",
      "url": "https://smmall.site"
    },
    {
      "title": "Levi Nunnink",
      "url": "https://nunn.ink"
    },
  ]
}

/link-list.html

<ul data-merge-repeat="links">
  <li>
    <a href="${url}">${title}</a>
  </li>
</ul>

<script data-type="merge-script">
  document.addEventListener(
    'DOMContentLoaded', 
    function() {
      merge.loadState('/link-list.json');
    }, 
  false);
</script>

<!-- 
  This will output all of the items in 
  the "links" JSON array as HTML.
-->

Codepen Example

How does it work?

The HTML child of data-merge-repeat will be repeated on the page with the contents of the JSON array mapping to the variables in the HTML. The HTML is interpreted using Javascript template string syntax.

We use the open-source Merge.js engine to power HTML includes. If you want to really see how this works, the source code is here: https://github.com/levinunnink/merge.js