nkint
nkint

Reputation: 11733

EJS - pass variable when include

I'm using ejs in backend with nodejs. I'd like to pass variable when include. When include the header, pass the page title.

index.ejs:

<% include header %>
<body> . . . </body>
<% include footer%>

header.ejs:

<html lang="en">
<head>
    <title><%- my_tytle %></title>
</head>

footer.ejs:

</html>

How to pass my_title in the include command?

Upvotes: 15

Views: 16794

Answers (4)

CoryCoolguy
CoryCoolguy

Reputation: 1080

<%- include("header", locals) %>

All variables that are accessible in index will also be available in header.

Upvotes: 1

loudo
loudo

Reputation: 53

As asked somewhere in the comments, we can also use a variable to be controled by a server, and here is how: <%- include("header",{my_tytle :`${myVar}`}) %>

Upvotes: 1

subrahmanya bhat
subrahmanya bhat

Reputation: 598

You can pass the object inside the include statement

<%- include("header",{title:"your_title"}) %>

Upvotes: 14

Naeem Shaikh
Naeem Shaikh

Reputation: 15715

you can pass my_tytle directly to the index.ejs and if there is a partial view for header, my_tytle should be accessible to the header.

for example: index.ejs:

<% include header %>
<body> . . . </body>
<% include footer%>

header.ejs:

<html lang="en">
<head>
    <title><%- my_tytle %></title>
</head>

now from node server if you pass the value for my_tytle to index.ejs, like this:

res.render('template_file.js', {
        my_tytle : "Value for your title"
    });

then your partial view (i.e header in your case) would be also able to access that variable.

Upvotes: 9

Related Questions