【问题标题】:Lodash _.template rendering escaped charactersLodash _.template 渲染转义字符
【发布时间】:2017-06-29 16:32:42
【问题描述】:

我已经从“控制器”中逃脱了一些数据:

<b>

而且我使用的是 lodash 模板 (_.template),在渲染时,它仍然是纯文本:

<b>

预期:

<b>

如何在没有浏览器的情况下呈现这种 html 部分,认为它就像纯文本而不是元素?

【问题讨论】:

    标签: javascript lodash underscore.js-templating html-escape-characters


    【解决方案1】:

    调用一个函数来取消转义 HTML。根据您的情况,您可以选择取消转义数据并将结果传递给模板,或者像在这个 sn-p 中一样,在模板中编写函数调用:

    var temp = _.template("<%= htmlDecode(name) %>");
    
    function htmlDecode(input) {
      var doc = new DOMParser().parseFromString(input, "text/html");
      return doc.documentElement.textContent;
    }
    
    console.log(temp({ name: "&lt;em&gt;Test&lt;/em&gt;" }));
    

    http://jsbin.com/laretumiqa/edit?html,js,console,output

    (htmlDecode函数来自这个问题:Unescape HTML entities in Javascript?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-14
      • 2015-06-27
      • 1970-01-01
      • 2013-02-04
      • 2023-03-13
      • 1970-01-01
      • 2021-07-15
      • 2017-08-04
      相关资源
      最近更新 更多