Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8926161
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T07:54:03+00:00 2026-06-15T07:54:03+00:00

I’m using mustache partials for our internal documentation and for testing – as described

  • 0

I’m using mustache partials for our internal documentation and for testing – as described in this other SO question how to have grunt task render mustache partials to static HTML, and I’d now like to make the partials data driven using external json files. The json files would be named the same as the partials and will contain mock data that would compile with the partials.

Any suggestions on how to get this working?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T07:54:04+00:00Added an answer on June 15, 2026 at 7:54 am

    I’ve updated the hogan.js file to read in data.json files that have the same name as the partials:

    module.exports = function(grunt) {
    
      // Grunt utilities.
      var task   = grunt.task,
        file     = grunt.file,
        utils    = grunt.util,
        log      = grunt.log,
        verbose  = grunt.verbose,
        fail     = grunt.fail,
        option   = grunt.option,
        config   = grunt.config,
        template = grunt.template,
        _        = utils._
    
      // external dependencies
      var fs   = require('fs'),
        hogan  = require('hogan');
    
    
      // ==========================================================================
      // TASKS
      // ==========================================================================
      grunt.registerMultiTask('hogan', 'Compile mustache files to HTML with hogan.js', function() {
    
        var data     = this.data,
          src        = grunt.file.expandFiles(this.file.src),
          dest       = grunt.template.process(data.dest),
    
          // Options are set in gruntfile
          defaults   = {
            production:  false,
            docs:        false,
            title:      'Sellside',
            setAccount: 'NA',
            setSiteId:  'NA',
            layout:     'docs/templates/layout.mustache',
            paths: {},
            partials: {},
            partialsData: {},
          },
    
          options = _.extend(defaults, this.data.options || {})
    
          !src && grunt.warn('Missing src property.')
          if(!src) return false
    
          !dest && grunt.warn('Missing dest property')
          if(!dest) return false
    
        var done         = this.async()
        var srcFiles     = file.expandFiles(src)
    
        if(options.paths.partials) {
    
          var partials = grunt.file.expandFiles(options.paths.partials);
          log.writeln('Compiling Partials...');
          partials.forEach(function(filepath) {
            var filename = _.first(filepath.match(/[^\\\/:*?"<>|\r\n]+$/i)).replace(/\.mustache$/, '');
            log.writeln(filename.magenta);
    
            var dataFilepath = filepath.replace(/\.mustache$/, '.json');
    
            var partial = fs.readFileSync(filepath, 'utf8');
            options.partials[filename] = hogan.compile(partial);
    
            // if a data file exists, read in the data
            if(fs.existsSync(dataFilepath)) {
              options.partialsData[filename] = grunt.file.readJSON(dataFilepath);
            }
    
          });
          log.writeln();
    }
    
        try {
          options.layout   = fs.readFileSync(options.layout, 'utf8')
          options.layout   = hogan.compile(options.layout, {
            sectionTags: [{
              o: '_i',
              c: 'i'
            }]
          })
        } catch(err) {
          grunt.warn(err) && done(false)
          return
        }
    
        srcFiles.forEach(function(filepath) {
          var filename = _.first(filepath.match(/[^\\\/:*?"<>|\r\n]+$/i)).replace(/\.mustache$/, '')
    
          grunt.helper('hogan', filepath, filename, options, function(err, result) {
            err && grunt.warn(err) && done(false)
            if(err) return
    
            file.write(dest.replace('FILE', filename), result)
          })
        })
    
        done()
      })
    
      // ==========================================================================
      // HELPERS
      // ==========================================================================
      grunt.registerHelper('hogan', function(src, filename, options, callback) {
        log.writeln('Compiling ' + filename.magenta);
    
        var page                = fs.readFileSync(src, 'utf8'),
            html                = null,
            layout              = options.layout,
            context             = {};
    
            context[filename]   = 'active';
            context._i          = true;
            context.production  = options.production;
            context.docs        = options.docs;
            context.setAccount  = options.setAccount;
            context.setSiteId   = options.setSiteId;
    
        var title               = _.template("<%= page == 'Index' ? site : page + ' · ' + site %>")
        context.title           = title({
          page: _(filename).humanize().replace('css', 'CSS'),
          site: options.title
        })
        try {
          page = hogan.compile(page, {
            sectionTags: [{
              o: '_i',
              c: 'i'
            }]
          })
    
          context = _.extend(context, options.partialsData);    
          options.partials.body = page;
          page = layout.render(context, options.partials)
    
          callback(null, page)
        } catch(err) {
          callback(err)
          return
        }
      })
    };
    

    A simple example of an alert.json file:

    {
      "modifier": "alert-warning",
      "alertType": "Warning!",
      "message": "Best check yo self, you're not looking too good."
    }
    

    alert.mustache

    alerts

      <div class="row-fluid">
        <div class="alert {{alert.modifier}}">
          <button type="button" class="close" data-dismiss="alert">&times;</button>
          <strong>{{alert.alertType}}</strong>
          {{alert.message}}
        </div>
      </div>
    
    </div><!-- /container -->
    

    I like this next example better because you can create different data to use
    in the same partials:

    alert.json

    {
      "default": {
        "modifier": "alert-warning",
        "alertType": "Warning!",
        "message": "Best check yo self, you're not looking too good.!"
      },
      "error": {
        "modifier": "alert-error",
        "alertType": "Error!!!",
        "message": "You did something horribily wrong!!!"
      },
      "success": {
        "modifier": "alert-success",
        "alertyType": "Success!!!",
        "message": "The record has been successfully saved..."
      }
    }
    

    alert.mustache

    <!-- partial -->
    <div class="container">
      <h1>alerts</h1>
    
      <div class="row-fluid">
        <div class="alert {{modifier}}">
          <button type="button" class="close" data-dismiss="alert">&times;</button>
          <strong>{{alertType}}</strong>
          {{message}}
        </div>
      </div>
    
    </div><!-- /container -->
    

    partials.mustache — this is where the alert partial is referenced

      {{#alert.default}}
        {{> alert }}
      {{/alert.default}}
    
      {{#alert.error}}
        {{> alert }}
      {{/alert.error}}
    
      {{#alert.success}}
        {{> alert }}
      {{/alert.success}}
    

    Let me know if this helps.

    Thanks,
    Brian

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
This could be a duplicate question, but I have no idea what search terms
this is what i have right now Drawing an RSS feed into the php,
I have this code to decode numeric html entities to the UTF8 equivalent character.
We're building an app, our first using Rails 3, and we're having to build
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
We are using XSLT to translate a RIXML file to XML. Our RIXML contains
I don't have much knowledge about the IPv6 protocol, so sorry if the question
I know there's a lot of other questions out there that deal with this

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.