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

1.2k Views Asked by At

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?

2

There are 2 best solutions below

3
On BEST ANSWER

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.

1
On

My project do that !

Light version https://github.com/thierryc/grunt-handlebars-layouts

This task has two required properties, src and dest. src is the path to your source file and dest is the file this task will write to (relative to the grunt.js file). If this file already exists it will be overwritten.

  files: {
    'dest.html': 'src.html'
  },

An example configuration looks like this:

  grunt.initConfig({
    handlebarslayouts: {
      home: {
        files: {
          'dist/home.html': 'src/home.html'
        },
        options: {
          partials: [
            'src/partials/*.hbs',
            'src/layout.html'
          ],
          modules: [
            'src/helpers/helpers-*.js'
          ],
          basePath: 'src/',
          context: {
            title: 'Layout Test',
            items: [
              'apple',
              'orange',
              'banana'
            ]
          }
        }
      }
    }
  });
  grunt.registerTask('default', ['handlebarslayouts']);

```