Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EJS: pass a variable to the included file

Tags:

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

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?

like image 579
Mihail Avatar asked Dec 24 '22 23:12

Mihail


1 Answers

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'}) %>
like image 151
Timothy Gu Avatar answered Jan 11 '23 01:01

Timothy Gu