Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clean pattern for localizing sentences in Rails i18n

I have the following sentence I need to localize:

you have U unread message/s and N new message/s

Example localization

U 0 N 1

"you have 1 new message"

U 1 N 1

"you have 1 unread message and 1 new message"

U 1 N 0

"you have 1 unread message"

U 2 N 0

"you have 1 unread messages"

I can easily get started with this mess

unread_only: 
  one: you have 1 unread message
  other: you have {{count}} unread messages 

new_only: 
  one: you have 1 new message
  other: you have {{count}} new messages 

... at this point I am stuck

# how do I pass two counts in?
new_and_unread:

I am aware i18n in Rails is not ICU MessageFormat, however, is there some sane way of localizing this with the tools we have? Can you pass 2 counts into a localization switch?

like image 262
Sam Saffron Avatar asked May 30 '13 00:05

Sam Saffron


1 Answers

My first thought is to use something like:

unread: 
  one: 1 unread message
  other:{{count}} unread messages 

new: 
  one: 1 new message
  other: {{count}} new messages 


I18n.t('you_have') << [msg1,msg2].map(&:presence).compact.join(I18n.t('and'))

But this probably won't work for every language. Just western ones.

Here is more info: http://guides.rubyonrails.org/i18n.html#passing-variables-to-translations

new_and_unread: "You have %{new} new, and %{unread} unread messages"

<%=t 'new_and_unread', :new => 1, :unread => 3 %>
like image 54
Matt Van Horn Avatar answered Nov 02 '22 09:11

Matt Van Horn