EJS:<%vs <%-->有什么区别

时间:2019-07-01 11:52:50

标签: node.js express ejs

EJS documentation总结了<%和<%-之间的差异,如下所示:

  

<%'Scriptlet'标签,用于控制流,无输出

     

<%=将值输出到模板中(已转义HTML)

     

<%-将未转义的值输出到模板中

但是,我注意到无论使用<%还是<%-,我都会得到相同的HTML输出,如下所示

<%# Include header %>
<% include partials/header %> //Using <%

<h1>This is the home page</h1>
<p>Some content goes here</p>

<%# Include footer %>
<%- include partials/footer %> //using <%-

这是我的header.ejs文件

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" type="text/css" href="/app.css">
    <title>Demo App</title>
</head>
<body>

我已经检查了以下问题(EJS: <%= versus <%-),但没有解释这种现象。

1 个答案:

答案 0 :(得分:1)

<%-<%标签的用途不同,第一个只是用于未转义的输出:

const template = '<%- user %>';
ejs.render(template, { user: 'Alice' }); // renders "Alice"

但是,假设有许多用户,在这种情况下,可能需要使用一些流控制结构来遍历用户,这是在使用<%的情况下:

const template2 = '<% users.map(user => { %> <%- user -%> <% }) %>';
ejs.render(template, { users: ['Alice', 'Bob'] }); // renders "Alice  Bob"

您可以验证,在这些示例中,标记<%-<%具有不同的行为并且不可互换。


您用include描述的情况非常特殊。我认为,预期的行为是不要输出partials/header(带有<%),因为它是一个简单的模板(而不是流控制)。

这就是现代include语法的工作方式,即,如果您尝试使用以下方法include头,则:

<% include("partials/header") %>

代替

<% include partials/header %>

您将看到没有输出。

对于旧式include语法,看来ejs<%<%-标记内均等对待。如果您想进一步调查此问题,检查库源代码可能会有所帮助:https://github.com/mde/ejs/blob/master/lib/ejs.js#L713

或者您可以简单地偏爱新的include语法,该语法似乎可以提供更一致的行为。

相关问题