【问题标题】:extract form labels for i18n in rails在rails中提取i18n的表单标签
【发布时间】:2021-07-15 09:56:46
【问题描述】:

阅读ActionView::Helpers::FormHelper,我看到它说:

标签的文本将默认为属性名称,除非在当前 I18n 语言环境中找到翻译(通过 helpers.label..)或您明确指定它。

因此,您应该能够为 post 资源上的 title 标签创建翻译,如下所示:

app/views/posts/new.html.erb

<% form_for @post do |f| %>
  <%= f.label :title %>
  <%= f.text_field :title %>
  <%= f.submit %>
<% end %>

config/locales/en.yml

en:
  helpers:
    label:
      post:
        title: 'Customized title'

config/locales/en.yml

en:
  activerecord:
    attributes:
      post:
        title: 'Customized title'

有什么方法可以自动提取所有表单标签并将它们的正确键添加到 i18n 语言环境文件中?与 i18n-tasks gem 对 I18n.t 定义的键所做的类似。

【问题讨论】:

  • 问题是你想重命名每个字段还是只重命名几个字段。或者您需要它们是因为您想支持其他语言环境?
  • 如果是第二个,我认为您可以通过循环所有 Models 并从模型中获取列/属性来获得它
  • 我想自动为所有语言环境文件添加键,以支持应用程序中启用的所有语言环境。像i18n-tasks add-missing这样的任务。
  • 我正在尝试为 i18n-tasks 编写自定义扫描器
  • 我看到有人为另一个用例写了such a custom scanner

标签: ruby-on-rails ruby-on-rails-5 rails-i18n i18n-tasks


【解决方案1】:

我找到了一个解决方案,对于任何想要处理所有用例的人来说,它肯定不会是一个通用的解决方案,这个解决方案只是处理来自 脚手架生成器 的默认输出,它会生成这样的表单标签:&lt;%= form.label :username %&gt;。这基本上是i18n-tasks gem 的扩展:

lib/tasks/scan_resource_form_labels.rb

require 'i18n/tasks/scanners/file_scanner'
class ScanResourceFormLabels < I18n::Tasks::Scanners::FileScanner
  include I18n::Tasks::Scanners::OccurrenceFromPosition

  # @return [Array<[absolute key, Results::Occurrence]>]
  def scan_file(path)
    text = read_file(path)
    text.scan(/^\s*<%= form.label :(.*) %>$/).map do |attribute|
      occurrence = occurrence_from_position(
          path, text, Regexp.last_match.offset(0).first)
      model = File.dirname(path).split('/').last
      # p "================"
      # p model
      # p attribute
      # p ["activerecord.attributes.%s.%s" % [model.singularize, attribute.first], occurrence]
      # p "================"
      ["activerecord.attributes.%s.%s" % [model.singularize, attribute.first], occurrence]
    end
  end
end

I18n::Tasks.add_scanner 'ScanResourceFormLabels'

config/i18n-tasks.yml

(在文件底部添加)

<% require './lib/tasks/scan_resource_form_labels.rb' %>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-31
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多