Ruby on rails 简单表单I18n标签
大家好,在我的应用程序中,我构建了一个搜索框。看起来是这样的:Ruby on rails 简单表单I18n标签,ruby-on-rails,internationalization,simple-form,Ruby On Rails,Internationalization,Simple Form,大家好,在我的应用程序中,我构建了一个搜索框。看起来是这样的: = simple_form_for :cars, {url: cars_path, method: :get} do |f| = f.input :handover_location, collection: Location.all.map{|hl| [hl.name, hl.id]} = f.input :return_location, collection: Location.all.map{|rl| [rl.nam
= simple_form_for :cars, {url: cars_path, method: :get} do |f|
= f.input :handover_location, collection: Location.all.map{|hl| [hl.name, hl.id]}
= f.input :return_location, collection: Location.all.map{|rl| [rl.name, rl.id]}
= f.input :car_class, collection: CarClass.all.map { |c| [c.name, c.id] }, include_blank: true
= f.submit
现在我不知道如何用I18n翻译这些标签。我怎样才能做到这一点呢?首先,我要先阅读,特别是第3部分。对于基于活动记录模型的表单,Rails具有一些定制的内置支持(请参阅文档的第4.6部分)。例如,要将您的
汽车
型号名称转换为“汽车”以外的其他名称,您可以执行以下操作:
# config/locales/en.yml
en:
activerecord:
models:
car:
one: Automobile
other: Automobiles
(替代您选择的支持I18n的语言。)
但是,一般来说,要使用I18n,可以调用Rails提供的translate
方法,缩写为t
。例如:
= simple_form_for :cars, {url: cars_path, method: :get} do |f|
..
= f.label t('forms.car_class')
= f.input :car_class, collection: CarClass.all.map { |c| [c.name, c.id] }, include_blank: true
..
= f.submit
# config/locales/en.yml
en:
forms:
car_class: 'Automobile'
这将使用文本“Automobile”呈现标签。查看有关i18n的简单表单文档: 它描述得很好,而且非常详细 例如(从文档中): 这将指定标签的默认值。 您应该查看文档,因为还有很多选项 其次,您也可以显式地这样做
= f.input :car, label: I18n.t('my_car_label'), prompt: I18n.t('my-car-prompt'), placeholder: I18n.t('my-placeholder')
我认为这是一个更好的答案,因为它关注于简单表单gem。简单表单文档没有“很好地描述”,因为示例只包含第二部分-字典,而该字典没有表单示例。从你的回答中,我无法理解“simple\u form\u for”标记的样子,或者你没有解释字典在问题中的形式应该是什么样子。虽然这并不难,文档也解释得很好,为什么我要重复它?总之,简单地说,你不需要修改表单中的任何内容,在翻译中你使用模型名,然后在更深的层次上写属性名,这对我来说是显而易见的。你需要一个更具体的例子吗?
= f.input :car, label: I18n.t('my_car_label'), prompt: I18n.t('my-car-prompt'), placeholder: I18n.t('my-placeholder')