使用可选参数在.yml中进行翻译

Bis*_*lli 33 yaml ruby-on-rails internationalization

我想my_translation用可选参数进行翻译.例如:

> I18n.t('my_translation')
=> "This is my translation"
> I18n.t('my_translation', parameter: 1)
=> "This is my translation with an optional parameter which value is 1"
Run Code Online (Sandbox Code Playgroud)

这可能吗?

Yan*_*hao 36

当然是.你只需写下这样的翻译:

my_translation: This is my translation with an optional parameter which value is %{parameter}
Run Code Online (Sandbox Code Playgroud)

参数真的是可选的吗?在上面的翻译中,您必须提供所有参数.

更新:对不起,我回答得太早了.我觉得这很容易.也许最简单的方法是这样的:

> I18n.t('my_translation1')
=> "This is my translation"
> I18n.t('my_translation2', parameter: 1)
=> "This is my translation with an optional parameter which value is 1"
Run Code Online (Sandbox Code Playgroud)


Pau*_*nti 19

我会说这是可能的,虽然不推荐.你有两个完全独立的字符串,根据你在@Yanhao的答案中的评论,我会说它们应该是你的yaml文件中的两个单独的条目:

report_name: My report
report_name_with_date: My report on %{date}
Run Code Online (Sandbox Code Playgroud)

由于date确定要显示哪个字符串的存在,您可以params在控制器方法的哈希中测试它的存在,将标题分配给变量,然后在视图中使用它.也许是这样的:

report_date = params[:report_date]
if report_date && report_date.is_a?(Date)
  @report_name = I18n.t('report_name_with_date', date: report_date.to_s)
else
  @report_name = I18n.t('report_name')
end
Run Code Online (Sandbox Code Playgroud)

如果你想要完全按照你所描述的行为,你需要两个yaml条目,并且你有额外的卷积,并且你将通过将两个字符串连接在一起创建一个字符串来做一个I18n no-no,这假定一个固定的语法句子结构(更不用说这会推动翻译人员在墙上):

report_name_with_date: My report%{on_date}
on_date: on %{date}
Run Code Online (Sandbox Code Playgroud)

用这样的代码:

report_date = params[:report_date]
if report_date && report_date.is_a?(Date)
  on_date = I18n.t('on_date', date: report_date.to_s)
  @report_name = I18n.t('report_name_with_date', on_date: " #{on_date}")
else
  @report_name = I18n.t('report_name_with_date', on_date: nil)
end
Run Code Online (Sandbox Code Playgroud)

所以,总而言之,我会说两个单独的整个字符串,就像在第一个例子中一样.