How can I pass variable to ejs.compile

Alexander picture Alexander · Mar 4, 2013 · Viewed 9.3k times · Source

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!

Answer

Vadim Baryshev picture Vadim Baryshev · Mar 4, 2013

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>