2017年12月31日日曜日

railsのplaceholderでi18n対応する

最近i18n対応することがあって、テキストのplacehodlerをどう国際化するのか不明だったので調べました。

まず書いてみたのはこんな感じ
= form_for(:user, url: 'xx') do |f|
  = f.text_field :last_name, { placeholder: t('activerecord.attributes.user.last_name'), required: true }
これだと、placeholderが翻訳できないエラーが出ました。
placeholder="<span class="translation_missing" title="translation missing: en.activerecord.attributes.user.last_name">Last Name</span>"


調べてみたところ、en.ymlにplacehodlerのhelper用の記述を加えて、form側の記述を変える必要があるようです。
・en.yml
en:
  helpers:
    placeholder:
      user:
        last_name: 'Last Name'

・form
= f.text_field :last_name, { placeholder: true, required: true }
これだとちゃんと言語が英語のときでもplaceholderがen.ymlに設定したLast Nameが表示されました。



参考URL
https://stackoverflow.com/questions/25677031/how-do-i-translate-placeholder-text-in-rails-4

0 件のコメント:

コメントを投稿