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!
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.
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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With