I18n
国际化具体的两个应用场景:
1.前端页面显示返回的validation的message,默认的是英语,这里可以手动改写为中文。
2.前端页面进行国际化,使用I18n.t方法。
3.将国际化的选择存储在数据库中或者cookie中。
4.解决locales下面的文件过多问题
场景1:validation的汉化过程
#建立示例
rails g scaffold Article title:string content:text
#model/article.rb
class Article<ActiveRecord::Base
validates :title, presence: {message: "标题不能为空"}
validates :content, presence: {message: "内容不能为空"}, length: {minimum: 3, message: "内容不能少于3个字符"}
end
#呈现示例,view中错误信息的罗列,不要使用rails默认错误样式表示方式,那样会出现空格以及各种样式问题
<ul>
<% @article.errors.messages.values.flatten.each do |error| %>
<li><%= error %></li>
<% end %>
</ul>
#显示的错误提示
标题不能为空
内容不能少于3个字符
内容不能为空
场景2:进行页面的国际化以及validation的国际化
#示例
rails g scaffold Article title:string content:text
#更改model/article.rb文件内容如下
class Article < ApplicationRecord
validates :title, presence: true
validates :content, presence: true, length: { minimum: 3 }
end
#配置文件config/application.rb,默认显示为中文
config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '*.{rb,yml}').to_s]
config.i18n.default_locale = :zh
config.encoding = 'utf-8'
#下载en.yml和zh.yml到文件夹config/locales中,并在相应的文件中增加如下的内容
#针对zh.yml文件增加下面内容
zh:
#翻译edit字段
edit: 编辑
#翻译model中的属性值
activerecord:
attributes:
article:
title: "标题"
content: "内容"
#针对en.yml文件增加下面内容
en:
edit: Edit
#修改app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
before_action :set_locale
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
end
end
#采用view中的默认的错误呈现方式
<ul>
<% @article.errors.full_messages.each do |error| %>
<li><%= error %></li>
<% end %>
</ul>
#使用t方法改变view中固定字段的显示样式
<%= link_to (t 'edit'), edit_article_path(article) %>
#在url中进行演示
http://localhost:3000/articles?locale=zh
http://localhost:3000/articles?locale=en
场景3:使用cookies或者数据库保存网站的locale值
在前面的两个应用场景中,项目采用默认的形式,第一个场景默认使用中文,第二个场景可以在中文和英文中进行切换,但是切换到其他链接中的时候,还是会返回为默认的locale形式,所以这里采用的做法是通过cookies或者数据库保存网站locale的值。
国际化中出现的错误方式国际化
zh:
views:
pagination:
first: "« 首页"
last: "末页 »"
previous: "‹ 上页"
next: "下页 ›"
truncate: "..."
activerecord:
attributes:
user:
name: "用户名"
email: "邮箱"
password: "密码"
password_confirmation: "密码确认"
errors:
models:
user:
attributes:
name:
blank: "不能为空"
email:
blank: "不能为空"
invalid: "格式不正确"
password:
blank: "不能为空"
too_short: "字符太短"
password_confirmation:
confirmation: "两次密码不一致"
4.解决locales下面的文件过多问题
一般情况下,locales下面一般都是zh.yml和en.yml文件,如果zh.yml文件中的内容过多,需要将这个文件分拆开来,下面是具体的配置方式
# config/application.rb
config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')]
#locales文件夹下面的文件排列配置
|-defaults
|---es.rb
|---en.rb
|-models
|---book
|-----es.rb
|-----en.rb
|-views
|---defaults
|-----es.rb
|-----en.rb
|---books
|-----es.rb
|-----en.rb
|---users
|-----es.rb
|-----en.rb
|---navigation
|-----es.rb
|-----en.rb