Search code examples
node.jsgruntjsmustachelivereload

How to configure Grunt serve/livereload to combine mustache templates


I'm using Yeoman template to develop a static web site. grunt serve nicely works with the auto reload plugin.

For repeating elements I started to use {{mustache}} partials and it works like a blast. Now I want the auto reload to assemble my page, so I can look at the resulting page when editing one of the mustache files (either a main file or a partial).

I found a grunt task for it, but stitching it together eludes me. My config looks like this:

grunt.initConfig({
  sass: {
    dev: {
      src: ['src/sass/*.sass'],
      dest: 'dest/css/index.css',
    },
  },
  watch: {
    sass: {
      // We watch and compile sass files as normal but don't live     reload here
      files: ['src/sass/*.sass'],
      tasks: ['sass']
    },
    mustache: {
    files: '**/*.mustache',
    tasks: ['mustache_render'],
    options: {
      interrupt: true
        },
    },  
    livereload: {
      options: { livereload: true },
      files: ['dest/**/*']
    }
  },
  mustache_render: {
    options: {
      {data: 'common-data.json'}
    },
    your_target: {
      files: [
        {expand: true,
        template: '**/*.mustache',
        dest: 'dest/'}
       ]
    }
  }
});

I must be missing something since the html files are not updated when I save the file.


Solution

  • You can add the livereload option directly to your mustache target options.

    grunt.initConfig({
      watch: {
        mustache: {
        files: '**/*.mustache',
        tasks: ['mustache_render'],
        options: {
          interrupt: true,
          livereload: true
          },
        }
      },
      mustache_render: {
        options: {
          {data: 'common-data.json'}
        },
        main: {
          files: [
            {expand: true,
            template: '**/*.mustache',
            dest: 'dest/'}
           ]
        }
      }
    });
    

    Also, if you're using grunt-contrib-connect to serve your files, don't forget to add the livereload option to it:

    connect: {
        http: {
          options: {
            hostname: "*",
            port: process.env.PORT || 80,
            livereload: true
          }
        }
      }