Skip to content

Instantly share code, notes, and snippets.

@boxxa
Created November 30, 2015 05:33
Show Gist options
  • Save boxxa/c1de9e7b4dc7c23c6da6 to your computer and use it in GitHub Desktop.
Save boxxa/c1de9e7b4dc7c23c6da6 to your computer and use it in GitHub Desktop.
Ghost doesn't has (doesn't have) Helper
// # Doesn't Has Helper
// Usage: `{{#dhas tag="video, music"}}`, `{{#dhas author="sam, pat"}}`
//
// Checks if a post doesn't have (doesn't has) a particular property for easy omitting in loop.
var _ = require('lodash'),
errors = require('../errors'),
dhas;
dhas = function (options) {
options = options || {};
options.hash = options.hash || {};
var tags = _.pluck(this.tags, 'name'),
author = this.author ? this.author.name : null,
tagList = options.hash.tag || false,
authorList = options.hash.author || false,
tagsOk,
authorOk;
function evaluateTagList(expr, tags) {
return expr.split(',').map(function (v) {
return v.trim();
}).reduce(function (p, c) {
return p || (_.findIndex(tags, function (item) {
// Escape regex special characters
item = item.replace(/[\-\/\\\^$*+?.()|\[\]{}]/g, '\\$&');
item = new RegExp('^' + item + '$', 'i');
if( item.test(c) )
return false
else
return true
}) !== -1);
}, false);
}
function evaluateAuthorList(expr, author) {
var authorList = expr.split(',').map(function (v) {
return v.trim().toLocaleLowerCase();
});
if( _.contains(authorList, author.toLocaleLowerCase()) )
return false
else
return true
}
if (!tagList && !authorList) {
errors.logWarn('Invalid or no attribute given to dhas helper');
return;
}
tagsOk = tagList && evaluateTagList(tagList, tags) || false;
authorOk = authorList && evaluateAuthorList(authorList, author) || false;
if (tagsOk || authorOk) {
return options.fn(this);
}
return options.inverse(this);
};
module.exports = dhas;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment