如何在 javascript 中使用 ejs 将字符串转换为 html 格式

How to convert string into html format using ejs in javascript

场景是用户将以 HTML 格式输入文本(例如 <\/b>Testing<\/b>),然后插入的文本将保存到数据库中(HTML 代码作为字符串(例如 <\b>Testing<\/b>).

我希望从数据库中取回的字符串显示为 HTML 文本(例如 Testing)。

我按照下面的代码片段操作,但没有得到任何输出。

注意:<%= cData.description %> 简单执行时工作正常,但显示 HTML 代码为纯文本。

test.js(路由文件):

var testid = 234123;
b.find(testid, function(data) {
  b.otherdet(testid, function(cdata){
    res.render('blogdesc',{
      Data: data,
      cdata: cdata
    });     
  });
});

test.ejs 文件:

<p class="" id="descid"></p>

<script>
  var $log = $( "#descid" );
  html = $.parseHTML('<%= cData.description %>'); //description is column in database
  $log.append( html );
</script>

shows how to emit HTML as-is in EJS, but please make sure that you sanitize 避免 XSS 的内容。

我找到了,哪里出错了。我正在使用:

html = $.parseHTML('<%=blogData.description%>');

而实际语法应该是这样的:

html = $.parseHTML('<%-blogData.description%>');