Rails:Javascript 字符串的国际化?

Rails: Internationalization of Javascript Strings?(Rails:Javascript 字符串的国际化?)
本文介绍了Rails:Javascript 字符串的国际化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我们现有的 Rails 2.3.5 应用程序根本不支持国际化.现在,我对 Rails I18n 的东西非常熟悉,但是我们在 /javascripts/ 中有很多输出字符串.我不是这种方法的忠实拥护者,但不幸的是,现在修复它为时已晚.

So, we have an existing Rails 2.3.5 app that does not support Internationalization at all. Now, I'm well familiar with Rails I18n stuff, but we have a LOT of output strings inside /javascripts/. I'm not a huge fan of this approach, but unfortunately it is too late to fix it now.

我们如何将存储在 Rails 应用程序中的 JS 文件中的字符串国际化?Rails 甚至不提供 JS 文件...

How might we internationalize strings stored in JS files in a Rails app? Rails doesn't even serve the JS files...

我想我总是可以让 Rails 应用程序提供 JS 文件,但这似乎很糟糕.有没有插件可以做到这一点?

I'm thinking I could always have the Rails app serve up the JS files, but that seems pretty gross. Are there plugins to do this?

推荐答案

为什么不做一些简单的事情:

Why not something simple like:

<script type="text/javascript">
  window.I18n = <%= I18n.backend.send(:translations).to_json.html_safe %>
</script>

然后在 JS 中你可以这样做:

Then in JS you can do things like:

I18n["en-US"]["alpha"]["bravo"];

我已经将我的包裹在一个应用程序助手中.

I've wrapped mine in an application helper.

def current_translations
  @translations ||= I18n.backend.send(:translations)
  @translations[I18n.locale].with_indifferent_access
end

然后我在 application.html.erb 中的调用如下所示:

Then my call in my application.html.erb looks like this:

<script type="text/javascript">
  window.I18n = <%= current_translations.to_json.html_safe %>
</script>

这使您不必知道 JavaScript 中的当前语言环境.

This allows you to avoid having to know the current locale in JavaScript.

I18n["alpha"]["bravo"];

或者

I18n.alpha.bravo;

这篇关于Rails:Javascript 字符串的国际化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)