put new line in string to translate

北慕城南 提交于 2019-12-22 06:48:22

问题


I'm using ngx-translate.

How can I put a line break in a string to translate ?

In my template I have :

{{'STRING_TO_TRANSLATE' | translate}}

In my en.json:

{
"STRING_TO_TRANSLATE": "text on first line. <br> or \n don't work. Text on second line"
}

回答1:


It works! But instead of

{{'STRING_TO_TRANSLATE' | translate}}

You should do

<div [innerHTML]="'STRING_TO_TRANSLATE' | translate"></div>

<br/>s should work just fine, but in other cases you may need some additional 'safe html pipe', i.e:

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({name: 'mySafeHtmlPipe'})
export class SafeHtmlPipe implements PipeTransform {
  constructor(private sanitizer: DomSanitizer) {
  }

  public transform(htmlContent) {
    return this.sanitizer.bypassSecurityTrustHtml(htmlContent);
  }
}



回答2:


Your can use \n but you will have to provide some styling.

So in your template use this:

<div class="my-translated-paragraph">
    {{'STRING_TO_TRANSLATE' | translate}}
</div>

Your en.json:

{
"STRING_TO_TRANSLATE": "text on first line.\nText on second line"
}

Your (s)CSS file:

.my-translated-paragraph{
    white-space: pre-wrap;
}

More info an the magic behind white-space: https://stackoverflow.com/a/42354356/3757110

See also a github Issue about this: https://github.com/angular-translate/angular-translate/issues/595




回答3:


If you want <p></p> for \n\n and <br /> for \n, here's my solution:

Step 1: Do as I say in this comment

Step 2: Chain your pipes likes this:

<div [innerHTML]="'YOUR_TRANSLATE_WITH_\n_OR_\n\n_GOES_HERE' | translate | nl2pbr"></div>

More information about chaining pipes here: https://angular.io/guide/pipes#chaining-pipes



来源:https://stackoverflow.com/questions/45819033/put-new-line-in-string-to-translate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!