【问题标题】:How to use a variable as a key with i18next?如何使用变量作为 i18next 的键?
【发布时间】:2019-12-23 05:07:34
【问题描述】:

我正在尝试将变量用作使用 i18next 进行本地化的键。虽然返回了正确的字符串,但插值不起作用。

我尝试使用变量和原始字符串来查看问题出在哪里。我确信它来自i18n.t() 中变量的使用。

return newChannel.guild.channels.get(config.defaultChannel).send(i18n.t(message.content, message.options));

message 值由函数返回。这是一个sn-p:

else if (newChannel.name !== oldChannel.name) {
    return message = {
        content: i18n.t('events:channel.update.name.text'),
        options: { oldChannel: `**#${oldChannel.name}**`, newChannel: newChannel, interpolation: { escapeValue: false }}
    };
}

即json中的字符串:

"update": {
    "name": {
        "text": "The text channel {{oldChannel}} is now called {{newChannel}}."
    }
}

它输出:The text channel is now called .

【问题讨论】:

  • 你能告诉我们message.contentmessage.options的内容吗?我假设一个是update.name.text,另一个应该包含oldChannelnewChannel。通常,插值是通过匹配键名来进行的,所以我会在不知道内容的情况下猜测您的内容不匹配。
  • 感谢阅读!我更新了我的问题:)。
  • 没有人可以帮助我吗? :(

标签: javascript node.js i18next


【解决方案1】:

这个 sn-p 看起来不正确:

else if (newChannel.name !== oldChannel.name) {
    return message = {
        content: i18n.t('events:channel.update.name.text'),
        options: { oldChannel: `**#${oldChannel.name}**`, newChannel: newChannel, interpolation: { escapeValue: false }}
    };
}

应该更像:

else if (newChannel.name !== oldChannel.name) {
    return message = {
        content: i18n.t('events:channel.update.name.text'),
        options: { oldChannel: oldChannel.name, newChannel: newChannel.name, interpolation: { escapeValue: false }}
    };
}

注意这两个变量的变化。你能解释一下你在映射中试图做什么,让你觉得你需要用 ES6 进行字符串插值,而不是仅仅使用库本身支持的插值?

【讨论】:

  • 感谢您的回答!您的修改改变了我想要显示的内容。 oldChannel.name**#${oldChannel.name}** 不同。我想我不明白你的问题是什么意思。我将 escapeValue 设置为 false,否则它不会以我想要的方式显示。
  • oldChannel.name 应该和**#${oldChannel.name}** 一样好;我只是在询问额外的插值。但是第二个变量newChannel 是一个对象,您似乎打算显示属性newChannel.name,这在您的示例中会失败。
  • 返回的对象可以用我用的这种方式显示。它返回一个作为链接的文本(这就是为什么将 escapeValue 设置为 false。这在其他地方有效。是因为我返回值消息以在其他地方使用它吗?在这种情况下,message.options 中的变量不是传输?
猜你喜欢
  • 2014-01-01
  • 1970-01-01
  • 2016-10-24
  • 1970-01-01
  • 2021-09-18
  • 1970-01-01
  • 1970-01-01
  • 2012-01-23
相关资源
最近更新 更多