Preventing HTML character entities in locale files from getting munged by Rails3 xss protection

后端 未结 5 1279
遇见更好的自我
遇见更好的自我 2021-02-03 23:58

We\'re building an app, our first using Rails 3, and we\'re having to build I18n in from the outset. Being perfectionists, we want real typography to be used in our views: dashe

5条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-04 00:35

    There is a ticket in lighthouse for this problem, and the resolution is to append _html to the i18n key in the locales/xx.yml file and use the t alias1 to denote an html_safe string. For example:

    en:
      hello: "This is a string with an accent: ó"
    

    becomes:

    en:
      hello_html: "This is a string with an accent: ó"
    

    And it would create the following output:

    This is a string with an accent: ó

    This would prevent you from having to write raw t('views.signup.organisation_details') and would result in a cleaner output of: t('views.signup.organisation_details_html'). And while exchanging raw for _html doesn't seem like the greatest of trades, it does make things clear that you're outputting what is assumed to be an html_safe string.


    1 I've tested the code suggested in the lighthouse ticket. What I found was that you had to specifically use the t alias. If you used I18n.t or I18n.translate the translation didn't treat _html as html_safe:

    I18n.t('hello_html') 
    I18n.translate('hello_html') 
    # Produces => "This is a string with an accent: ó"
    
    t('hello_html')      
    # Produces => "This is a string with an accent: ó"
    

    I don't think this is the intended behavior per the RoR TranslationHelper documentation.

提交回复
热议问题