EJS:将变量传递给包含的文件
EJS: pass a variable to the included file
我正在使用 EJS 作为我的前端开发堆栈的一部分。
例如我的正常 index.ejs 看起来像这样:
<%- include parts/header.ejs %>
<%- include parts/navigation.ejs %>
<!-- HTML content: divs, spans, etc. -->
<%- include parts/footer.ejs %>
我想要的是以某种方式传递一个带有 include <%- include parts/footer.ejs?variable=value %> 的变量并想在其中读取它包含的文件,有条件地 show/hide 某些部分的内容。
我找不到方法。 EJS 可以吗?
两种方法:
愚蠢的方式
这种方式兼容EJS 1.0,优点是编译时。
只需在 include
ing 之前声明变量即可。
示例:
included.ejs:
<p><%= variable %></p>
main.ejs:
<% var variable = 'hola' %>
<% include included %>
聪明的方式
此方法仅适用于 EJS 2.0 或更新版本,但可能比最后一种方法稍慢(如果未启用缓存则慢很多):
included.ejs:
<p><%= variable %></p>
main.ejs:
<%- include('included', {variable: 'hola'}) %>
我正在使用 EJS 作为我的前端开发堆栈的一部分。 例如我的正常 index.ejs 看起来像这样:
<%- include parts/header.ejs %>
<%- include parts/navigation.ejs %>
<!-- HTML content: divs, spans, etc. -->
<%- include parts/footer.ejs %>
我想要的是以某种方式传递一个带有 include <%- include parts/footer.ejs?variable=value %> 的变量并想在其中读取它包含的文件,有条件地 show/hide 某些部分的内容。
我找不到方法。 EJS 可以吗?
两种方法:
愚蠢的方式
这种方式兼容EJS 1.0,优点是编译时。
只需在 include
ing 之前声明变量即可。
示例:
included.ejs:
<p><%= variable %></p>
main.ejs:
<% var variable = 'hola' %>
<% include included %>
聪明的方式
此方法仅适用于 EJS 2.0 或更新版本,但可能比最后一种方法稍慢(如果未启用缓存则慢很多):
included.ejs:
<p><%= variable %></p>
main.ejs:
<%- include('included', {variable: 'hola'}) %>