Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EJS - pass variable when include

Tags:

ejs

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?

like image 615
nkint Avatar asked May 21 '14 16:05

nkint


People also ask

How do you pass a variable in EJS?

It is possible to access JS variable in . ejs file. You just need to pass the JS object as second parameter of res. render() method.

What is locals in EJS?

Locals represent server-side data that is accessible to your view—locals are not actually included in the compiled HTML unless you explicitly reference them using special syntax provided by your view engine. <div>Logged in as <a><%= user.fullName %></a>.</


Video Answer


2 Answers

You can pass the object inside the include statement

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

like image 75
subrahmanya bhat Avatar answered Oct 11 '22 19:10

subrahmanya bhat


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.

like image 40
Naeem Shaikh Avatar answered Oct 11 '22 19:10

Naeem Shaikh