Search code examples
javascriptgruntjsassemble

How to generate HTML pages with Grunt using views and layouts?


I'm just starting to use Grunt in my projects. My typical project includes a layout file and several view files. I'd like to generate one HTML page per view file using the layout file.

For example, here is a layout file:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Some title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <!-- some css -->
  </head>
  <body>

  <!-- some js -->
  </body>
</html>

and a view file:

<h1>Lorem</h1>
<p>Some other stuff</p>

The result I'm hoping to get is:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Some title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <!-- some css -->
  </head>
  <body>

    <h1>Lorem</h1>
    <p>Some other stuff</p>

  <!-- some js -->
  </body>
</html>

Based on a quick Google Search, there are many plugins that say they can generate HTML, such as grunt-html-build and grunt-generator. I took a closer look at grunt-html-build, but it does not seem to fit my needs. So which Grunt plugin should I use so that I can get the results I want?


Solution

  • You could just use a simple series of HTML partials and Grunt Concat to piece them together.

    Your Gruntfile would look like this:

    concat:
      partials:
        options:
          process: true
        files:
          # destination as key, sources as value
          "dist/index.html": ["partials/_header.html", "partials/_home-page.html", "partials/_footer.html"]
    

    EDIT:

    I've moved to using Assemble for this task. Assemble also lets you use Handlebars and a data source to generate your HTML.