'Angular i18n with em and strong?
I'm preparing an application for internationalization with the @angular/localize
library, so I'm going through and adding i18n
attributes to fields that contain copy.
I've run into some difficulty where I have paragraphs of text that contain em
and strong
tags.
As an example:
<p>We are <em>very</em> happy that you've chosen Funtimes Widget Company!</p>
The application also uses 'strong' for certain product names in copy:
<p>Furthermore, when you take advantage of this deal, we'll send you a <strong>Super
Cool Widget Kit</strong> for no extra charge!</p>
I'm not sure how to handle this. Do I put the i18n
attribute on the parent p
tag? (I know that splitting an English sentence into chunks and translating each chunk separately is not the answer, because languages differ greatly in sentence structure.) How do emphasis (eg italics) and strong get handled in i18n?
- Angular 13.3.5.
Solution 1:[1]
I imagine that a solution can be a "work-around" that is you not use "tags" else replace the tag with "somedifferent" and use a pipe.
Imagine you has a pipe like
@Pipe({
name: 'htmlTag'
})
export class HtmlTagPipe implements PipeTransform {
constructor(protected sanitizer: DomSanitizer) {}
transform(value: any, args?: any): any {
if (!value)
return null;
return this.sanitizer.bypassSecurityTrustHtml(value.replaceAll('[','<')
.replaceAll(']','>'))
}
}
You can use an html like
<p [innerHtml]="greet.innerHTML | htmlTag"></p>
<!--in a wrapper with display:none you has differents "divs"-->
<div style="display:none">
<div #greet i18n="@@greet">hello [strong]world[/strong]</div>
</div>
Since Angular 13 you can translate variables in code, see the docs (sorry, I didn't use)
So I imagine you can to have in code some like
$localize `hello [strong]world[/strong]${variable}`;
And use
<p [innerHtml]="variable | htmlTag"></p>
Solution 2:[2]
We internationalize the markup as well. It's not pretty, it's not puristic: It just works as it also allows you to """internationalize""" the emphasized text.
We use ngx-translate
and the code looks kind of like this:
// en.json
{
"Widget1": {
"title": "This is <i>very</i> fun",...
}
}
// es.json
{
"Widget1": {
"title": "Esto es <i>muy</i> divertido",...
}
}
Then we have the component:
<app-card>
<h2 translate>Widget1.title</h2>
...
</app-card>
This also allows us to share the translation JSON's (we use a script to translate from JSON to XML in Android and to .strings in iOS) with our native Apps as for instance in Android it supports something called "SpannedString" which is text with style which you can easily use by using a helper method.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | pjpscriv |
Solution 2 | Some random IT boy |