如何使用Aurelia将换行符渲染为<br>标记

Vid*_*dar 5 html javascript aurelia aurelia-binding

我正在使用JSON检索一些文本数据,这些数据包括使用换行符格式化的文本.我非常想将这些换行符渲染给用户.

问题:实现这一目标的"正确"/"推荐"方法是什么?

我试过的选项:

  • 通常绑定<p>${myText}</p>::不呈现换行符
  • 使用<pre>:: <p><pre>${myText}></pre></p>渲染换行符,但包含长<pre>文本的所有已知和喜爱的问题,例如某些浏览器中的水平滚动和次优字断.
  • 通常使用valueConverter进行绑定,该值使用<br>标记替换换行符:<p>${myText | textFormat}</p>
export class TextFormatValueConverter {
  toView(value) {
    return value.replace(new RegExp('\r?\n','g'), '<br>');
  }
}
Run Code Online (Sandbox Code Playgroud)

这会渲染<br>标签,但Aurelia活页夹会转义标签并将其显示为用户的文字文本.*使用上面的转换器绑定和innerHTML :: <p innerHTML.bind="myText | textFormat"></p>渲染确定但是我担心它可能容易受到攻击,因为文本来自遗留系统,它不对网络的使用做任何输入清理.

Jer*_*yow 4

你正在做的事情是正确的。绑定innerHTML有时是必要的。aurelia.io上的文档包括使用清理转换器的说明以及有关使用sanitize-html项目进行更完整实现的说明。

也就是说,您可以创建一个真正轻量级的自定义属性,它只执行您需要的操作:

http://plnkr.co/edit/qykvo9PKAD0TawTlQ5sp?p=preview

保留-breaks.js

import {inject} from 'aurelia-framework';

function htmlEncode(html) {
  return document.createElement('a').appendChild( 
    document.createTextNode(html)).parentNode.innerHTML;
}

@inject(Element)
export class PreserveBreaksCustomAttribute {
  constructor(element) {
    this.element = element;
  }

  valueChanged() {
    let html = htmlEncode(this.value);
    html = html.replace(/\r/g, '').replace(/\n/g, '<br/>');
    this.element.innerHTML = html;
  }
}
Run Code Online (Sandbox Code Playgroud)

应用程序.js

export class App {
  message = `this is my text
it has some line breaks
and some <script>evil javascript</script>
the line breaks were replaced with <br/> tags`;
}
Run Code Online (Sandbox Code Playgroud)

应用程序.html

export class App {
  message = `this is my text
it has some line breaks
and some <script>evil javascript</script>
the line breaks were replaced with <br/> tags`;
}
Run Code Online (Sandbox Code Playgroud)