ejs中的for循环

For loops in ejs

我有一个数组,其中包含一些 html 这样的内容。

const articleArray=['<p>first text</p>\r\n','<p>second text></p>\r\n','<p>third text</p>\r\n']

我需要通过 get 请求在 ejs 文件中呈现它

request.render('viewArticles',{array : articleArray})

其中 'viewArticles' 是一个 ejs 文件。我已经使用中间件将视图引擎设置为 ejs。 这是ejs

中的代码
<% for(arr in array) {%>
    arr
<% } %>

我无法渲染任何 html。如何解决这个问题?

试试这个

<% array.forEach(function(item,index){ %>
        <%= item %> 
    <% }) %>

我不太确定如何准确地执行您想要的操作,但请看一下:

首先,与其创建 HTML 个元素的数组,不如创建一个对象数组,如下所示:

const articles = [{text: "first text"} , {text: "second text"}, {text: "third text"}];

这样你只需要写一次 HTML,我对编程还很陌生,但我没有看到你会在 HTML 中得到响应的场景,通常你查询数据库中的数据或从 JSON 文件...并假设数组实际上已传递到 .ejs 文件,让我们遍历它,

<% for(let a of articles){ %>

    <p> <%= a.text %> </p> 
    </br>

<% } %>


如果数组未通过,请在您的代码中检查这些内容:

// If you installed 
..."dependencies" : {
     "ejs": "x.x.x", 
} //Check the package.json file
// If you imported correctly
import ejs = require("ejs");

// If you specified the views path
app.set("views", path.join(__dirname, "views"));

// And the views engine
app.set("view engine", "ejs");

// And your route
request.render('viewArticles',{ articles : articles }) // Check if the file name is correct, I get this wrong many times

'<%- %>' 这有助于按原样打印 html 代码。

  • <% 'Scriptlet' 标签,用于控制流,无输出
  • <%_ ‘Whitespace Slurping’ Scriptlet 标签,去掉它前面的所有空格
  • <%= 将值输出到模板中(HTML 转义)
  • <%- 将未转义的值输出到模板中
  • <%# 注释标签,不执行,不输出
  • <%% 输出文字 '<%'
  • %> 普通结束标签
  • -%> Trim-mode ('newline slurp') 标签,在换行符后修剪
  • _%> ‘Whitespace Slurping’ 结束标签,移除其后的所有空格

    参考请点击访问本站EJS

    <% array.forEach(function(item) {%> <%-item%> <% }) %>