Reputation: 4208
I want to create a sentence that can be singular or plural based on the count
parameter:
# When count is 1
"This profile still contains 1 post"
# When count is 2
"This profile still contains 2 posts"
Using Rails i18n mechanism, I believe I have to embed Ruby code to get the correct pluralization for the word "post". I'm trying to build it like this, but it's not working:
# config/locales/en.yml
en:
message: "This profile still contains %{count} <%= Post.model_name.human(count: count).lowercase %>"
# Output of I18n.translate(:message, count: 2)
"This profile still contains 2 <%= Post.model_name.human(count: count).lowercase %>"
I already tried <%= %>
, %{ }
, #{ }
and {{ }}
and all failed.
Is it even possible to embed Ruby code in i18n file? How?
Upvotes: 0
Views: 1391
Reputation: 5609
Use the pluralize
method :
config/locales/en.yml
en:
message: "This profile still contains"
view
"#{I18n.t('message')} #{Post.count} #{Post.model_name.human.pluralize(Post.count).downcase}."
#=> output : "This profile still contains 1 post." or "This profile still contains XX posts"
It works but i recommend you to put all the view logic in a helper.
Note : i use global Post.count
for the example but you can use any count you want as user.posts.count
etc...
Upvotes: 0
Reputation: 2624
According to the docs, you should do something like this:
en:
message:
one: This profile still contains 1 post
other: This profile still contains %{count} posts
And call it:
I18n.t('message', count: count)
Hope it helps!
Upvotes: 5