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?
Two ways to do this:
This way is compatible with EJS 1.0, and has the advantage of being compile-time.
Just declare the variables right before include
ing.
Example:
included.ejs:
<p><%= variable %></p>
main.ejs:
<% var variable = 'hola' %>
<% include included %>
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'}) %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With