Skip to content

Basic example with handlebars

ismay edited this page Apr 14, 2019 · 1 revision

You can use metalsmith-layouts with metalsmith's Javascript API or the CLI. For this example we'll use the cli:

Install metalsmith and metalsmith-layouts:

$ npm install metalsmith metalsmith-layouts

Install appropriate jstransformers

In this case we'll use handlebars, so we'll also need to install jstransformer-handlebars:

$ npm install jstransformer-handlebars

Configure metalsmith

We'll create a metalsmith.json configuration file, and a file for metalsmith-layouts to process:

./metalsmith.json

{
  "source": "src",
  "destination": "build",
  "plugins": {
    "metalsmith-layouts": true
  }
}

For this example we're creating a single .html file in src, but you can create as many as you need:

./src/index.html

---
title: The title of this page
layout: layout.hbs
---
<p>Some text for the page here. This will be inserted in the `contents` variable in the handlebars template.</p>

We'll put the html that's similar across all our pages in our handlebars layout, so we won't have to repeat it everywhere. If necessary you can of course have multiple layouts, but for now we'll use a single one:

./layouts/layout.hbs

<!doctype html>
<html>
  <head>
    <title>{{ title }}</title>
  </head>
  <body>
    {{{ contents }}}
  </body>
</html>

Build

To build just run the metalsmith CLI (note that you'll need npm@5.2.0 or higher to use npx):

$ npx metalsmith

Which will output the following file:

./build/index.html

<!doctype html>
<html>
  <head>
    <title>The title of this page</title>
  </head>
  <body>
    <p>Some text for the page here. This will be inserted in the `contents` variable in the handlebars template.</p>
  </body>
</html>