ruby-on-rails - 在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
定义的键所做的类似。
解决方案
我找到了一个解决方案,对于任何想要处理所有用例的人来说,它肯定不会是一个通用的解决方案,这个解决方案只是处理来自脚手架生成器的默认输出,该生成器生成如下表单标签:<%= form.label :username %>
. 这基本上是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'
配置/i18n-tasks.yml
(在文件底部添加这个)
<% require './lib/tasks/scan_resource_form_labels.rb' %>
推荐阅读
- php - vue.js:[Vue 警告]:编译模板时出错:+ 在 laravel 刀片文件中
- javascript - 使用计时器触发的 Azure javascript 函数检索不记名访问令牌时出现问题
- python - 一个热门编码器的 categorical_features 用于什么?
- django - 如何在html模板中使用for循环
- electron - 在 Electronjs 中使用 Javascript Webspeech Api
- xml - 如果元素具有具有特定 id 的附加属性,则更改属性的值
- bixby - 上次 6.10.0-r19i.8185 BixbyStudio 之后的变化
- git - git:如何只允许访问某些文件夹(不是所有 repo)?回购在 Windows 服务器上
- python - 如何在 Django 模板中显示模型功能
- email - Bot Framework 电子邮件通道响应时间慢