如何使用 Aurelia 将换行符呈现为 <br> 标签

How to render linebreaks as <br> tags with Aurelia

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

问题: "correct" / "recommended" 实现这个的方法是什么?

我试过的选项:

export class TextFormatValueConverter {
  toView(value) {
    return value.replace(new RegExp('\r?\n','g'), '<br>');
  }
}

这确实呈现 <br> 标签,但 Aurelia 活页夹转义标签并将它们作为文字文本显示给用户。 * 使用上述转换器和 innerHTML 进行绑定:<p innerHTML.bind="myText | textFormat"></p>:呈现正常,但我担心它可能容易受到攻击,因为文本来自遗留系统,该系统不对使用进行任何输入清理网络。

问题是 Aurelia 将您转换后的 HTML 呈现为转义标签。要解决这个问题,只需使用您的 RegExp 函数转换为 <br>,然后像这样使用内部 HTML 绑定:

<p innerHTML.bind=“htmlText”>${myText}</p>

这将阻止 Aurelia 逃离 HTML。我看到您担心使用这种方法,因为您担心某处可能存在错误 HTML,但没有其他方法可以解决此问题,因为您无法告诉 Aurelia 仅呈现特定标签。

如果您 担心潜在的不良 HTML,您为什么不编写一段自定义 JS 来取消转义所有 <br> 页面加载后的标签? (丑得要命,但我看不到其他方式。)

你的做法是正确的。有时需要绑定到 innerHTMLaurelia.io include instructions for using a sanitization converter and a note about using a more complete implementation using the sanitize-html 项目中的文档。

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

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

preserve-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;
  }
}

app.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`;
}

app.html

<template>
  <require from="./preserve-breaks"></require>

  <div preserve-breaks.bind="message"></div>
</template>

我找到了解决方案 on Githubstyle="white-space: pre-wrap;" 在父元素上的使用修复了问题。