panini icon indicating copy to clipboard operation
panini copied to clipboard

Macro to differentiate between pages on different paths

Open dagostinelli opened this issue 6 years ago • 4 comments

When there is just one file called index.html this works fine:

$ cat header.html
{{#ifpage 'index'}}
You are at the home page
{{/ifpage}}

But when there are multiple directories with an index.html per directory, this code need to be enhanced (but how?)

The request is for some kind of differentiator to indicate the path to the file. The result might be something like this:

$ cat header.html
{{#ifpage '/index'}}
You are at the home page
{{/ifpage}}

{{#ifpage '/articles/index'}}
You are in the articles section
{{/ifpage}}

{{#ifpage 'index'}}
You are on some random page named index
{{/ifpage}}

dagostinelli avatar Apr 30 '18 03:04 dagostinelli

anyone a solution or workaround? this is a really annoying bug

guyvanbael avatar Jun 20 '18 14:06 guyvanbael

I have the same problem! any ideas!?.

1V4NR4ND0M avatar Aug 31 '18 02:08 1V4NR4ND0M

same.

etanb avatar Dec 14 '18 21:12 etanb

I created a helper to fulfill my needs, maybe it helps you too. Unfortunately it does not really check the path, which seems not to be possible (we have no parent context), but for my need of detecting blog posts it helped (like <a href="/blog/overview" class="{{#ifpagewildcard 'overview' '20*'}}is-active{{/ifpagewildcard}}">Blog</a>. Therefore I prefix the pages with the date (2020-... and am able to detect at least this one.

helpers/ifpagewildcard.js

module.exports = function() {
  /**
   * Handlebars block helper that renders the content inside of it based on the current page.
   * @param {string...} pages - One or more pages to check.
   * @param (object) options - Handlebars object.
   * @example
      {{#ifpagewildcard 'over*view'}}<p>over*view</p>{{/ifpagewildcard}}
      {{#ifpagewildcard 'ove*iew'}}<p>ove*iew</p>{{/ifpagewildcard}}
      {{#ifpagewildcard '*view'}}<p>*view</p>{{/ifpagewildcard}}
      {{#ifpagewildcard 'over*'}}<p>over*</p>{{/ifpagewildcard}}
      {{#ifpagewildcard '*ervie*'}}<p>*ervie*</p>{{/ifpagewildcard}}
      {{#ifpagewildcard '*ervie'}}<p>*ervie NOT SHOWN</p>{{/ifpagewildcard}}
      {{#ifpagewildcard 'vervie*'}}<p>vervie* NOT SHOWN</p>{{/ifpagewildcard}}
   * @return The content inside the helper if a page matches, or an empty string if not.
   */
  const allAsterisks = new RegExp(/\*/, 'g');

  var params = Array.prototype.slice.call(arguments);
  var pages = params.slice(0, -1);
  var options = params[params.length - 1];
  var pageName = options.data.root.page;
  
  for (var i in pages) {
    const tester = new RegExp('^' + pages[i].replace(allAsterisks, '.*') + '$');
    if (tester.test(pageName)) {
      return options.fn(this);
    }
  }

  return '';
}

maxmarkus avatar Aug 05 '20 09:08 maxmarkus