EJS: pass a variable to the included file

南笙酒味 提交于 2020-06-25 04:44:07

问题


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 %>

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.

I can't find the way to do it. Is it possible with EJS?


回答1:


Two ways to do this:

Dumb Way

This way is compatible with EJS 1.0, and has the advantage of being compile-time.

Just declare the variables right before includeing.

Example:

included.ejs:

<p><%= variable %></p>

main.ejs:

<% var variable = 'hola' %>
<% include included %>

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:

<p><%= variable %></p>

main.ejs:

<%- include('included', {variable: 'hola'}) %>


来源:https://stackoverflow.com/questions/28430012/ejs-pass-a-variable-to-the-included-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!