node.js: is there no way to put HTML into i18n-nod

2019-06-16 16:59发布

问题:

The question says it all. If I put HTML directly into the (JSON-formatted) translation file, like this:

"test_html" : "click <a href='http://stackoverflow.com/'>here</a>",

I get this in my HTML:

click &lt;a href=&#39;http://stackoverflow.com/&#39;&gt;here&lt;/a&gt;

I also tried combining this in my translation file:

"test_html_placeholder" : "click %shere%s",

With this in my HTML:

<%= __('test_html_placeholder', '<a href="http://stackoverflow.com">', '</a>') %>

But got similar results.

The only thing I can get to work is this clumsiness:

"test_html_pre" : "click ",
"test_html_link" : "here",
"test_html_post" : ".",

with this:

<%= __('test_html_pre') %><a href="http://stackoverflow.com"><%= __('test_html_link') %></a><%= __('test_html_post') %>

But it's so cumbersome as to be almost not worth doing, and moreover the word order in some languages would force me to put some empty strings in my translation files, which i18n-node doesn't seem to like as it spits out the key (attribute) name when it encounters an empty string.

I also tried using "\" as an escape character in front of the symbols, but I got an invalid JSON error when I lifted sails (restarted the server).

Any ideas, workarounds? I'm using sails.js, it wasn't my decision but I'm stuck with it and it comes with i18n-node. It's kind of late in the day on this project to consider using another library, but not completely out of the question.

回答1:

beside of any upcoming discussion whether to include (html-)code in language files or not:

try to use

<%- __('<a href="#">click</a>') %>

instead of

<%= __('<a href="#">click</a>') %>

in ejs (the sails default template engine) a '<%=' will escape any html tags while '<%-' puts output as is without touching it. I am pretty sure you'll find unescaped html in your .json files. i18n doesn't do any transformation other than JSON.stringify() but almost all template engines do escape strings by default to prevent xssi.



回答2:

For those using pug/jade, you can use

!{ __('key_for_your_text') }