Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass variable to ejs.compile

Tags:

node.js

ejs

My bottom_index.ejs looks like that:

<div>The bottom section</div>

In my code I declare ejs:

ejs = require('ejs');

Then compile the function:

var botom_index_ejs =
ejs.compile(fs.readFileSync(__dirname + "/../views/bottom_index.ejs", 'utf8'));

and then call it to get rendered html:

botom_index_ejs()

It works fine!

Now I would like to change my template to:

<div><%= bottom_text %></div>

and be able to pass the parameter (bottom_text) to the bottom_index.ejs

How should I pass the parameters?

Thanks!

like image 467
Alexander Avatar asked Mar 04 '13 12:03

Alexander


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.

Can you declare variables in EJS?

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 I move data from one page to another in EJS?

If you want to pass the variable from one page to the other all users just to reduce duplication then you should use include to include that in all pages that need it or to pass it by the handlers.

How do I include in EJS?

Now you can include them in your views. Use <% - include( 'RELATIVE/PATH/TO/FILE' ) %> to embed an EJS partial in another file. The hyphen <%- instead of just <% to tell EJS to render raw HTML. The path to the partial is relative to the current file.


1 Answers

Parameters are passed to EJS template as a JS plain object. For your example it sholud be:

botom_index_ejs({ bottom_text : 'The bottom section' });

Update:

test.js

var fs = require('fs');
var ejs = require('ejs');
var compiled = ejs.compile(fs.readFileSync(__dirname + '/test.ejs', 'utf8'));
var html = compiled({ title : 'EJS', text : 'Hello, World!' });
console.log(html);

test.ejs

<html>
    <head>
        <title><%= title %></title>
    </head>
    <body>
        <p><%= text %></p>
    </body>
</html>
like image 156
Vadim Baryshev Avatar answered Oct 23 '22 05:10

Vadim Baryshev