如何在 node.js EJS 视图中转义 HTML?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16183748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 07:49:39  来源:igfitidea点击:

How to escape HTML in node.js EJS view?

htmlnode.jsejs

提问by marko

I want to escape the html in bloglist[i].Text field. How to do that with EJS?

我想转义 bloglist[i].Text 字段中的 html。如何用 EJS 做到这一点?

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <h1><%= title %></h1>
    <p>Welcome to <%= title %></p>
    <% for(var i=0; i < bloglist.length; i++) { %>
       <h3> <%= bloglist[i].Title %></h3>
       <div>
          <%= bloglist[i].Text %>
       </div>
    <% } %>
  </body>
</html>

回答by Julian Lannigan

You are escaping the value correctly by using:

您正在使用以下方法正确转义该值:

<%= bloglist[i].Text %>

If you want to allow HTML to be rendered, then you want an "unescaped" value. To do that use the following:

如果要允许呈现 HTML,则需要一个“未转义”值。为此,请使用以下命令:

<%- bloglist[i].Text %>

All I did was replace the equal (=) with a dash (-).

我所做的只是用破折号 (-) 替换等号 (=)。

Reference: https://github.com/visionmedia/ejs/tree/0.8.3#features

参考:https: //github.com/visionmedia/ejs/tree/0.8.3#features