Rails 的單複數翻譯

紅寶鐵軌客
Join to follow...
Follow/Unfollow Writer: 紅寶鐵軌客
By following, you’ll receive notifications when this author publishes new articles.
Don't wait! Sign up to follow this writer.
WriterShelf is a privacy-oriented writing platform. Unleash the power of your voice. It's free!
Sign up. Join WriterShelf now! Already a member. Login to WriterShelf.
寫程式中、折磨中、享受中 ......
659   0  
·
2017/08/01
·
1 mins read


這一定要寫下來,就在剛要放棄時,突然仔細看了文件,證明,要看書,不要老是在網路找解答。

 

Rails 的 I18n 有很好用的翻譯 YAML,以前我都是用條件判斷來做單複數翻譯:

# config/locales/en.yml

en:
1error: You have 1 error
errors: You have %{counter} errors

<%# app/views/errors/index.html.erb %>

<% if @err.count == 1 %>
<%= t("1error") %>
<% else %>
<%= t("errors", counter: @err.count) %>
<% end %>

日子照過,今天想要來改成 Rails I18n 自己判斷功能,想所少寫些,結果,搞了20分鐘,就是不動! 

# config/locales/en.yml

en:
errors:
one: You have 1 error
other: You have %{counter} errors

<%# app/views/errors/index.html.erb %>

<%= t("errors", counter: @err.count) %>

為什麼,為什麼,為什麼,為什麼,為什麼⋯⋯

就在要放棄時,看到Rails文件上的一段附註:

The :count interpolation variable has a special role in that it both is interpolated to the translation and used to pick a pluralization from the translations according to the pluralization rules defined by CLDR:

為什麼要規定變數名稱啊,不能改名? 所以,改成用Count就好了:

# config/locales/en.yml

en:
errors:
one: You have 1 error
other: You have %{count} errors

<%# app/views/errors/index.html.erb %>

<%= t("errors", count: @err.count) %>

20分鐘又學到:「讀書很重要!」


WriterShelf™ is a unique multiple pen name blogging and forum platform. Protect relationships and your privacy. Take your writing in new directions. ** Join WriterShelf**
WriterShelf™ is an open writing platform. The views, information and opinions in this article are those of the author.


Article info

分類於:
標籤:
日期:
創作於:2017/08/01,最後更新於:2017/10/27。
合計:265字


Share this article:
About the Author

很久以前就是個「寫程式的」,其實,什麼程式都不熟⋯⋯
就,這會一點點,那會一點點⋯⋯




Join the discussion now!
Don't wait! Sign up to join the discussion.
WriterShelf is a privacy-oriented writing platform. Unleash the power of your voice. It's free!
Sign up. Join WriterShelf now! Already a member. Login to WriterShelf.