如何使用 i18n 本地化 Stimulus JS 值?
我正在开发 Rails 6 应用程序,我试图将所有显示的字符串存储在语言环境文件中。我有一个名为 countdown_controller.js
的 Stimulus 控制器:
import { Controller } from "@hotwired/stimulus";
export default class extends Controller {
static values = {
message: { type: String, default: "Deal closed!" }
}
}
en.yml:
en:
deals:
status:
closed: "Deal closed!"
我想使用 I18n.t("deals.status.close")
作为 countdown_controller.js
中 messageValue
的值,而不是直接写入字符串。我不知道该怎么做。
I am working on rails 6 application where I'm trying to store all displayed strings in locales files. I have a Stimulus controller named countdown_controller.js
:
import { Controller } from "@hotwired/stimulus";
export default class extends Controller {
static values = {
message: { type: String, default: "Deal closed!" }
}
}
en.yml
:
en:
deals:
status:
closed: "Deal closed!"
I want to use I18n.t("deals.status.closed")
as a value for messageValue
in countdown_controller.js
instead of directly writing the string. I am not sure how to do that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我还发现很难使用 Stimulus 控制器实现本地化,直到我找到一个线程 - 对我的情况非常有帮助
I also find it hard to implement localization with Stimulus controller until I found a thread - very helpful in my case
只需将
countdown_controller.js
转换为countdown_controller.js.erb
对我来说很有效。然后我使用插值来注入I18n.t("deals.status.close")
如下:PS 当我将注释更改为使用以
#
而不是以//
开头的 JS 语法。Simply converting
countdown_controller.js
tocountdown_controller.js.erb
worked for me. Then I used interpolation to inject theI18n.t("deals.status.closed")
as follows:P.S. I was getting an error initially as I changed the comment to use ruby syntax which begins with
#
instead of JS syntax which begins with//
.我所做的是将翻译作为 Stimulus 控制器元素数据集的一部分发送,因此可以在
connect
上使用。就我而言,有多个,因此我从视图或助手发送一个哈希,如下所示:What I do is to send the translations as part of the Stimulus controller element dataset, so it's available on
connect
. In my case there is more than one, so I send a hash from the view or the helper, like this: