2014-10-10 18:54:07 +04:00
|
|
|
// # Has Helper
|
|
|
|
// Usage: `{{#has tag="video, music"}}`, `{{#has author="sam, pat"}}`
|
|
|
|
//
|
|
|
|
// Checks if a post has a particular property
|
|
|
|
|
|
|
|
var _ = require('lodash'),
|
2016-10-04 18:33:43 +03:00
|
|
|
logging = require('../logging'),
|
2015-11-12 15:29:45 +03:00
|
|
|
i18n = require('../i18n'),
|
2014-10-10 18:54:07 +04:00
|
|
|
has;
|
|
|
|
|
|
|
|
has = function (options) {
|
|
|
|
options = options || {};
|
|
|
|
options.hash = options.hash || {};
|
|
|
|
|
2016-06-11 21:23:27 +03:00
|
|
|
var tags = _.map(this.tags, 'name'),
|
2014-10-10 18:54:07 +04:00
|
|
|
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, '\\$&');
|
2015-01-10 00:52:23 +03:00
|
|
|
item = new RegExp('^' + item + '$', 'i');
|
2014-10-10 18:54:07 +04:00
|
|
|
return item.test(c);
|
|
|
|
}) !== -1);
|
|
|
|
}, false);
|
|
|
|
}
|
|
|
|
|
|
|
|
function evaluateAuthorList(expr, author) {
|
|
|
|
var authorList = expr.split(',').map(function (v) {
|
|
|
|
return v.trim().toLocaleLowerCase();
|
|
|
|
});
|
|
|
|
|
2016-06-11 21:23:27 +03:00
|
|
|
return _.includes(authorList, author.toLocaleLowerCase());
|
2014-10-10 18:54:07 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
if (!tagList && !authorList) {
|
2016-10-04 18:33:43 +03:00
|
|
|
logging.warn(i18n.t('warnings.helpers.has.invalidAttribute'));
|
2014-10-10 18:54:07 +04:00
|
|
|
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 = has;
|