Подтвердить что ты не робот

Как передать переменную ejs.compile

Мой bottom_index.ejs выглядит так:

<div>The bottom section</div>

В моем коде я объявляю ejs:

ejs = require('ejs');

Затем скомпилируйте функцию:

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

а затем вызвать его, чтобы получить визуализированный html:

botom_index_ejs()

Он отлично работает!

Теперь я хотел бы изменить свой шаблон на:

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

и иметь возможность передать параметр (bottom_text) в bottom_index.ejs

Как передать параметры?

Благодарю!

4b9b3361

Ответ 1

Параметры передаются в шаблон EJS в виде простого объекта JS. Для вашего примера это будет:

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

Обновить:

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>