Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to include a template with parameters in EJS?

Tags:

ejs

As a real beginner in EJS, I have two charts in my html page, so I want to use my partial twice:

<% include partials/spider-chart.ejs %> 

But I need to pass some parameters inside the ejs to differentiate between graphs.

What is the best way?

like image 622
Orkun Ozen Avatar asked Mar 22 '15 16:03

Orkun Ozen


People also ask

How do I create a variable in EJS template?

A variable declaration starts with the keyword var followed by the variable name, e.g. : var myVariable; The variable declaration ends with a semi-colon. The names of the variables in EJS-templates are case-sensitive: myVariable and myvariable are different variables.

How do you use variables 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.


2 Answers

@Naeem Shaikh solution works. Though include also gives you more intuitive way of including a partial template and also passing context variables to that as found in documention section of ejs.

<ul>   <% users.forEach(function(user){ %>       <%- include('user/show', {user: user}); %>   <% }); %> </ul> 
like image 58
Zubair Alam Avatar answered Nov 25 '22 19:11

Zubair Alam


I think you want to render two different charts using same partial ejs template, just by providing different data(within the main ejs file).

You can just define a variable, which will be assigned to the data, which the first chart will use, than include the chart.ejs file, again change the data, and include the partial ejs file(chart.ejs) again, so now you have two files which can use same variable(data), but can plot different chart based on value assigned to data.

For Example:

<% var data= 'data to be used by first chart(parameter)'; %> <% include partials/spider-chart.ejs %>  // re-initializing data for second chart <% data= 'data to be used by second chart(parameter)'; %> <% include partials/spider-chart.ejs %> 

where your spider-chart.ejs file could be something which will use data

spider-chart.ejs

    <li>         <%= data %> // just an example     </li> 

here, as you use data, the data variable accessed by both charts will be different because you are reassigning values for data before every chart.

like image 29
Naeem Shaikh Avatar answered Nov 25 '22 19:11

Naeem Shaikh