【问题标题】:How to escape ejs tags inside an ejs template string?如何在 ejs 模板字符串中转义 ejs 标签?
【发布时间】:2017-02-08 09:24:58
【问题描述】:

我们如何在模板中转义 ejs 标签本身?

在sails 中我想将以下代码放在layout.ejs 中

<!--STYLES-->
<% if (typeof head_css != 'undefined') { %>
  <%= head_css %>
<% } else { %>
  <% if (typeof head_css_before != 'undefined') { %>
    <%= head_css_before %>
  <% } %>
    <link rel="stylesheet" href="/styles/importer.css">
  <% if (typeof head_css_after != 'undefined') { %>
    <%= head_css_after %>
  <% } %>
<% } %>
<!--STYLES END-->

但默认情况下,&lt;!--STYLES--&gt;&lt;!--STYLES END--&gt; 中的所有内容都被此模板替换:

<link rel="stylesheet" href="%s">

sails-linker.js

所以我想代替模板&lt;link rel="stylesheet" href="%s"&gt; 放一些更复杂的东西,而不是渲染时的结果:

<!--STYLES-->
<% if (typeof head_css != 'undefined') { %>
  <%= head_css %>
<% } else { %>
  <% if (typeof head_css_before != 'undefined') { %>
    <%= head_css_before %>
  <% } %>
    <link rel="stylesheet" href="/styles/importer.css">
  <% if (typeof head_css_after != 'undefined') { %>
    <%= head_css_after %>
  <% } %>
<% } %>
<!--STYLES END-->

但问题是当我尝试类似

<%= special_code_here %><link rel="stylesheet" href="%s">

这是自动渲染的。我需要在 ejs 模板中转义 &lt;%

我们怎样才能做到这一点?

【问题讨论】:

  • 您是否尝试过&amp;lt;&amp;gt; 的HTML 实体,即&amp;lt;&amp;gt;
  • @ScottMarcus 是的,我试过了。这个问题在 layout.ejs 文件中呈现为 html 实体,我应该有非转义的&lt;%。所以在浏览器中出现了我想要的代码,但作为纯文本。

标签: javascript ejs


【解决方案1】:

&lt;%% 转义 EJS 标签,并给你&lt;%

这里是文档: EJS

如果我正确理解您的问题,这应该会有所帮助。

【讨论】:

  • 我已经尝试过了,但没有成功。看起来像风帆(我使用的框架在ejs-locals 中使用了旧版本的ejs)。我也尝试更新 ejs-locals 中的 ejs,但仍然无法正常工作。但是因为我的问题是关于 ejs 我会接受这个答案。我在 ejs 中就这个问题提出了一个问题,那个人关闭了这个问题,根本没有帮助我解决问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-07
  • 2015-09-18
  • 2021-03-22
  • 2020-09-04
  • 2020-08-15
  • 1970-01-01
相关资源
最近更新 更多