2010-12-07 48 views
10

我使用自動錶單標籤助手來創建我的表單標籤並通過i18n支持翻譯它們,但是,我想在標籤中使用HTML,而且我不能弄清楚如何使HTML安全。Rails 3:在i18n窗體幫助器翻譯中使用HTML

例如:

en: 
    helpers: 
    label: 
     product: 
     name: 'Your Product Name <small>Try to be creative</small>' 

結束爲:

<label for="product_name">Your Product Name &lt;Try to be creative&gt;</label> 

但我希望它是:

<label for="product_name">Your Product Name <small>Try to be creative</small></label> 

有我指定轉換的一種方式html_safe,以便它在輸出前不被編碼?另外,這似乎是要設置HTML的最有語義的方式,但如果我完全以錯誤的方式處理這些問題,我很樂意提供建議。

謝謝:)

更新時間:

<%= form_for @product do |f| %> 
    <%= f.label :name %> 
    <%= f.text_field :name %> 
<% end %> 

回答

12

不知道你的實際幫助是怎麼一回事,但是你可以使用html_safe做到這一點很容易(前提是你的標籤的價值將無法輸入由其他用戶)。

是這樣的:t("helpers.label.product.name").html_safe

如果不工作,請給你的你的helper方法,或僅用於輸出結果行執行。

====== UPDATED ======

感謝您的更新代碼,現在我知道什麼是最好的答案:d

我不太多,如果你真的想知道helpers.label.product.name

但還有另一種方式,我認爲會更好,這是定義爲他以下幾點:

en: 
    activerecord: 
    attributes: 
     product: 
     labels: 
      name: "Your Product Name <small>Try to be creative</small>" 

如果你不想建立自己的自定義表單生成器,使用:

= f.label :name, Product.human_attribute_name("labels.name").html_safe 

實際上,如果您定義了自己的表單生成器,那麼很容易重新定義標籤方法以自動生成它的文本。

+0

我使用的是標準的Rails助手:http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i -label – 2010-12-07 03:26:02

14

在rails3中自動生成正常密鑰的安全方式是將_html或.html附加到密鑰名稱。例如。 NAME_HTML。這隻能通過視圖中的translate/t方法工作,即不能通過I18n.t。這不會在這裏工作,儘管標準表單助手不會嘗試該版本的密鑰。

創建自己的表單構建器是建議的方式。你也可以做

f.label :name, t('helpers.label.product.name_html') 

如果這隻發生在幾個地方。

-8

另一種選擇是做到以下幾點:

name: '<span>Your Product Name <small>Try to be creative</small></span>'