HTML tags in i18next translation

前端 未结 8 1388
小鲜肉
小鲜肉 2020-12-08 18:30

I\'m using i18next to power i18n for my weblog. It works great on text-only content, but when I try to translate content that includes HTML markup, it is displaying the raw

相关标签:
8条回答
  • 2020-12-08 19:08

    Don't put the HTML tags in the translation. It's a bad idea anyway. Separation of concerns guys will be all whiny about it.

    Use the <Trans> component if react-i18next [https://react.i18next.com/latest/trans-component][1]

    Do like so:

    // Component.js
    
    <Trans>Welcome, <strong>User!</strong>, here's your <strong>broom</strong></Trans>
    

    And the corresponding translation file:

    // your locales/starwars_en.js file
    
    translations: {
      "Welcome, <1>User!</1>, here's your <3>broom</3>": "Welcome, <1>young padawan!</1>, here's your <3>light saber</3>",
    }
    

    These numbers <1> and <3> will strike you as random but wait for it:

    Trans.children = [
      'Welcome, ',                        // index 0
      '<strong>User!</strong>'            // index 1
      ', please don't be ',               // index 2
      '<strong>weak</strong>',            // index 3
      ' unread messages. ',               // index 4
    ]
    

    More info here: https://stackoverflow.com/a/62563302/537648

    0 讨论(0)
  • 2020-12-08 19:13

    I'm using both React and React Native. For the React app The solution works. Not for React Native.

    React
    i18n.js

    interpolation: {
          escapeValue: false   
        }
    

    somefile.jsx

    <div dangerouslySetInnerHTML={{__html: t('dropZone.description')}} />
    

    React Native
    This solution does not work because < div> is not allowed within a Text tag. I tried to add the dangerouslySetInnerHTML to the Text tag, but then nothing is visible.

    Does someone have a solution for React Native?

    0 讨论(0)
提交回复
热议问题