首页 > 解决方案 > 在rails中提取i18n的表单标签

问题描述

阅读ActionView::Helpers::FormHelper,我看到它指出:

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

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

app/views/posts/new.html.erb

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

配置/语言环境/en.yml

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

或者

配置/语言环境/en.yml

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

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

标签: ruby-on-railsruby-on-rails-5rails-i18ni18n-tasks

解决方案


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

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'

配置/i18n-tasks.yml

(在文件底部添加这个)

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

推荐阅读