问题描述
我将EJS用作前端开发堆栈的一部分.例如我正常的index.ejs看起来像这样:
I'm using EJS as a part of my front-end dev stack.For example my normal index.ejs looks like that:
<%- include parts/header.ejs %>
<%- include parts/navigation.ejs %>
<!-- HTML content: divs, spans, etc. -->
<%- include parts/footer.ejs %>
我想通过某种方式将包含<%-include parts/footer.ejs的变量传递给 variable = value %>,并希望有条件地在包含的文件中读取它显示/隐藏内容的某些部分.
What I want is to pass somehow a variable with the include <%- include parts/footer.ejs?variable=value %> and want to read it in the included file, to conditionally show/hide some parts of the content.
我找不到解决办法.EJS有可能吗?
I can't find the way to do it. Is it possible with EJS?
推荐答案
执行此操作的两种方法:
Two ways to do this:
这种方式与EJS 1.0兼容,并且具有编译时的优势.
This way is compatible with EJS 1.0, and has the advantage of being compile-time.
只需在 include
之前声明变量.
示例:
included.ejs:
included.ejs:
<p><%= variable %></p>
main.ejs:
<% var variable = 'hola' %>
<% include included %>
智能方式
此方法仅适用于EJS 2.0或更高版本,但可能比上一种方法稍慢(如果未启用缓存,则可能慢很多):
Smart Way
This method is only available with EJS 2.0 or newer, but might be marginally slower (or a lot slower if caching is not enabled) than the last method:
included.ejs:
included.ejs:
<p><%= variable %></p>
main.ejs:
<%- include('included', {variable: 'hola'}) %>
这篇关于EJS:将变量传递到包含的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!