2014-10-10 18:54:07 +04:00
|
|
|
// # Plural Helper
|
2018-01-09 16:50:57 +03:00
|
|
|
// Usage example: `{{plural ../pagination.total empty='No posts' singular='1 post' plural='% posts'}}`
|
|
|
|
// or for translatable themes, with (t) translation helper's subexpressions:
|
|
|
|
// `{{plural ../pagination.total empty=(t "No posts") singular=(t "1 post") plural=(t "% posts")}}`
|
2014-10-10 18:54:07 +04:00
|
|
|
//
|
2018-01-09 16:50:57 +03:00
|
|
|
// Pluralises strings depending on item count
|
2014-10-10 18:54:07 +04:00
|
|
|
//
|
|
|
|
// The 1st argument is the numeric variable which the helper operates on
|
|
|
|
// The 2nd argument is the string that will be output if the variable's value is 0
|
|
|
|
// The 3rd argument is the string that will be output if the variable's value is 1
|
|
|
|
// The 4th argument is the string that will be output if the variable's value is 2+
|
|
|
|
|
2021-09-23 22:46:22 +03:00
|
|
|
const {errors, tpl, SafeString} = require('../services/proxy');
|
2020-03-30 23:23:02 +03:00
|
|
|
const isUndefined = require('lodash/isUndefined');
|
2014-10-10 18:54:07 +04:00
|
|
|
|
2021-09-23 22:46:22 +03:00
|
|
|
const messages = {
|
|
|
|
valuesMustBeDefined: 'All values must be defined for empty, singular and plural'
|
|
|
|
};
|
|
|
|
|
2017-04-04 19:07:35 +03:00
|
|
|
module.exports = function plural(number, options) {
|
2020-03-30 23:23:02 +03:00
|
|
|
if (isUndefined(options.hash) || isUndefined(options.hash.empty) ||
|
|
|
|
isUndefined(options.hash.singular) || isUndefined(options.hash.plural)) {
|
2016-10-06 15:27:35 +03:00
|
|
|
throw new errors.IncorrectUsageError({
|
2021-09-23 22:46:22 +03:00
|
|
|
message: tpl(messages.valuesMustBeDefined)
|
2016-10-06 15:27:35 +03:00
|
|
|
});
|
2014-10-10 18:54:07 +04:00
|
|
|
}
|
|
|
|
|
2016-02-21 21:48:44 +03:00
|
|
|
if (number === 0) {
|
2017-04-04 19:07:35 +03:00
|
|
|
return new SafeString(options.hash.empty.replace('%', number));
|
2016-02-21 21:48:44 +03:00
|
|
|
} else if (number === 1) {
|
2017-04-04 19:07:35 +03:00
|
|
|
return new SafeString(options.hash.singular.replace('%', number));
|
2016-02-21 21:48:44 +03:00
|
|
|
} else if (number >= 2) {
|
2017-04-04 19:07:35 +03:00
|
|
|
return new SafeString(options.hash.plural.replace('%', number));
|
2014-10-10 18:54:07 +04:00
|
|
|
}
|
|
|
|
};
|