mirror of
https://github.com/TryGhost/Ghost.git
synced 2024-12-01 13:54:35 +03:00
7abcc43907
closes #5617 - Replace all hard-coded server-side strings with i18n translations
85 lines
2.2 KiB
JavaScript
85 lines
2.2 KiB
JavaScript
// # Foreach Helper
|
|
// Usage: `{{#foreach data}}{{/foreach}}`
|
|
//
|
|
// Block helper designed for looping through posts
|
|
var hbs = require('express-hbs'),
|
|
_ = require('lodash'),
|
|
errors = require('../errors'),
|
|
i18n = require('../i18n'),
|
|
|
|
hbsUtils = hbs.handlebars.Utils,
|
|
foreach;
|
|
|
|
foreach = function (context, options) {
|
|
if (!options) {
|
|
errors.logWarn(i18n.t('warnings.helpers.foreach.iteratorNeeded'));
|
|
}
|
|
|
|
var fn = options.fn,
|
|
inverse = options.inverse,
|
|
columns = options.hash.columns,
|
|
length = _.size(context),
|
|
limit = options.hash.limit || length,
|
|
output = '',
|
|
data,
|
|
contextPath;
|
|
|
|
if (options.data && options.ids) {
|
|
contextPath = hbsUtils.appendContextPath(options.data.contextPath, options.ids[0]) + '.';
|
|
}
|
|
|
|
if (hbsUtils.isFunction(context)) {
|
|
context = context.call(this);
|
|
}
|
|
|
|
if (options.data) {
|
|
data = hbs.handlebars.createFrame(options.data);
|
|
}
|
|
|
|
function execIteration(field, index, last) {
|
|
if (data) {
|
|
data.key = field;
|
|
data.index = index;
|
|
data.number = index + 1;
|
|
data.first = index === 0;
|
|
data.last = !!last;
|
|
data.even = index % 2 === 1;
|
|
data.odd = !data.even;
|
|
data.rowStart = index % columns === 0;
|
|
data.rowEnd = index % columns === (columns - 1);
|
|
|
|
if (contextPath) {
|
|
data.contextPath = contextPath + field;
|
|
}
|
|
}
|
|
|
|
output = output + fn(context[field], {
|
|
data: data,
|
|
blockParams: hbsUtils.blockParams([context[field], field], [contextPath + field, null])
|
|
});
|
|
}
|
|
|
|
function iterateCollection(context) {
|
|
var count = 1;
|
|
|
|
_.each(context, function (item, key) {
|
|
if (count <= limit) {
|
|
execIteration(key, count - 1, count === length);
|
|
}
|
|
count += 1;
|
|
});
|
|
}
|
|
|
|
if (context && typeof context === 'object') {
|
|
iterateCollection(context);
|
|
}
|
|
|
|
if (length === 0) {
|
|
output = inverse(this);
|
|
}
|
|
|
|
return output;
|
|
};
|
|
|
|
module.exports = foreach;
|