🐛 Fixed error in translate helper when invalid parameters are passed (#20663)

ref https://linear.app/tryghost/issue/SLO-182
ref https://github.com/TryGhost/Ghost/issues/15500

- when the {{ t }} helper is used with no parameter or an empty string,
it now returns an empty string
- when the {{ t }} helper is used without options, it now does not throw
an error
This commit is contained in:
Sag 2024-07-25 14:45:23 +02:00 committed by GitHub
parent 42398ce525
commit 1422ad5e6f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 29 additions and 12 deletions

View File

@ -11,18 +11,11 @@
// {{tags prefix=(t " on ")}}
const {themeI18n} = require('../services/handlebars');
const errors = require('@tryghost/errors');
const tpl = require('@tryghost/tpl');
const messages = {
oopsErrorTemplateHasError: 'Oops, seems there is an error in the template.'
};
module.exports = function t(text, options) {
if (text === undefined && options === undefined) {
throw new errors.IncorrectUsageError({
message: tpl(messages.oopsErrorTemplateHasError)
});
module.exports = function t(text, options = {}) {
if (!text || text.length === 0) {
// no-op: translation key is missing, return an empty string
return '';
}
const bindings = {};

View File

@ -165,7 +165,7 @@ class I18n {
let matchingString;
// no path? no string
if (msgPath.length === 0 || !isString(msgPath)) {
if (!msgPath || msgPath.length === 0 || !isString(msgPath)) {
this._handleEmptyKeyError();
return '';
}

View File

@ -53,4 +53,28 @@ describe('{{t}} helper', function () {
rendered.should.eql('Top left Button');
});
it('returns an empty string if translation key is an empty string', function () {
let rendered = t.call({}, '', {
hash: {}
});
rendered.should.eql('');
});
it('returns an empty string if translation key is missing', function () {
let rendered = t.call({}, undefined, {
hash: {}
});
rendered.should.eql('');
});
it('returns a translated string even if no options are passed', function () {
themeI18n.init({activeTheme: 'locale-theme', locale: 'en'});
let rendered = t.call({}, 'Top left Button');
rendered.should.eql('Left Button on Top');
});
});