Mo Programming
Mo Programming

Reputation: 21

How to add variable inside of .EJS template

I have an index page and an about page and a contact page. I also have a header.ejs file . Inside of header.ejs I have this:

<a href="/">Home</a> |
<a href="/about">My Resume</a> |
<a href="contact">My Contact Info</a>
<br>
_______________________________________

-----------------------------------------
<br>


<h3>Copyright 2019  Some text here</h3>

I would like to use the exact same header file for the index about and contact pages. I would like the content for each page to vary. This content is to be placed inside of the solid and dashed lines. I cannot use separate header files. I can only use one. How do I use this same template, but create space and fill it with different content for each page? Here is an example of my index file:

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
  <%include templates/header.ejs%>
    <h1><%= title %></h1>
    <p>Welcome to <%= title %></p>
  </body>
</html>

Upvotes: 2

Views: 3372

Answers (2)

Lord Elrond
Lord Elrond

Reputation: 16002

When you use the include function, you must omit the .ejs.

For example, on your index.ejs:

<%- include 'templates/header' %>

If you want to reuse the same template, you should put all "optional" content that you might decide to render, on a separate .ejs file, then whenever a condition is met, you can do the following:

somePage.ejs:

<p>Welcome to <%= title %></p>

someOtherPage.ejs:

<p>Goodbye <%= title %></p>

index.ejs:

<%- include 'templates/header' %>

<% if (someVar == true) { %>
<%- include 'somePage' %>
<% } %>

<% else if (someOtherVar == true) { %>
<%- include 'someOtherPage' %> 
<% } %>

Finally, on your app.js:

app.get('somePath', function(req, res) {
  res.render('index', {someVar:true, someOtherVar:false}); //pass variables to template like this
});

Upvotes: 0

Saurabh Mistry
Saurabh Mistry

Reputation: 13669

add variable page in your header file :

<a href="/">Home</a> |
<a href="/about">My Resume</a> |
<a href="contact">My Contact Info</a>
<% if(page=='home') { %>
  // add your home page header content here 
<% }else if(page=='contact'){%>
 // add your contact page header content here 
<% }else if(page=='resume'){%>
 // add your resume page header content here 
<% }else{ %>
  // default header
<% } %>
<h3>Copyright 2019  Some text here</h3>

include it by passing page variable :

for home page :

<%- include('templates/header', {page: 'home'}); %>

for contact page :

<%- include('templates/header', {page: 'contact'}); %>

Upvotes: 1

Related Questions