Search code examples
assemble

How to include var in partials calls


Let's say I have a website where for each main section I have a specific sidebar.

Currently I have a single sidebar file, where im using categories to filter the correct content to show like this:

   {{#inArray page.categories "Components"}}
    <section class="sg-index">
    <ul>
      <li {{#is title "DetailContent"}} class="active"{{/is}}>
        <a href="c-DetailContent.html">DetailContent</a>
      </li>

However my goal is to have these sidebar files located at each section folder, along with the section files.

How can I include the {{dirname}} variable in the partials call {{> sidebar}}?


Solution

  • This should be possible with a conditional block helper, like {{with}} and the include helper,

    B you could also create a custom helper, something like this:

    var path = require('path');
    var _ = require('lodash');
    var matter = require('gray-matter');
    
    module.exports.register = function (Handlebars, options, params) {
    
      var assemble = params.assemble;
      var grunt = params.grunt;
      var opts = options || {};
    
      Handlebars.registerHelper('sidenav', function(page, context) {
        if(page.published !== false && page.sidenav) {
    
          if(!Array.isArray(assemble.partials)) {
            assemble.partials = [assemble.partials];
          }
    
          var filepath = _.first(_.filter(assemble.partials, function(fp) {
            return path.basename(fp, path.extname(fp)) === page.sidenav;
          }));
    
          // Process context, using YAML front-matter,
          // grunt config and Assemble options.data
          var pageObj = matter(filepath) || {};
          var metadata = pageObj.context || {};
    
          context = _.extend(this, opts.data[page.sidenav], metadata, context);
          var partial = Handlebars.partials[page.sidenav];
          var template = Handlebars.compile(partial);
          var output = template(context);
    
          // Prepend output with the filepath to the original partial
          // for debugging
          var sidenav = opts.sidenav || opts.data.sidenav || {};
          if(sidenav.origin === true) {
            output = '<!-- ' + filepath + ' -->\n' + output;
          }
          return new Handlebars.SafeString(output);
        }
      });
    };
    

    then use it in your markup like this:

    <div class="sidebar" role="complementary">
      <ul class="nav sidenav">
        {{sidenav this}}
      </ul>
    </div>