有没有办法在 EJS 中包含/渲染变量?
Is there a way to Include / Render a variable in EJS?
有没有办法让包含的内容来自变量而不是来自文件?
我需要从数据库而不是文件中获取包含的内容,我想做这样的事情:
example.ejs 的内容:
<h1>Example EJS template<h1>
<p><%- include(data.includeCode) %><p>
带有 EJS 代码的 Nodejs/Express:
let includeCode = `<% if (data.dSwitch === 1) { %> 1 detected <% } else { %> Something else <% } %>`
let ejsdata = {...{includeCode: includeCode}, ...{dSwitch: 1}};
res.render("example.ejs",{data:ejsdata});
我想看到的是以下输出:
<h1>Example EJS template</h1>
<p> 1 detected </p>
我尝试使用 <%- data.includeCode %> 但输出为
<h1>Example EJS template</h1>
<p> <% if (data.dSwitch === 1) { %> 1 detected <% } else { %> Something else <% } %> </p>
解决方法是从ejs模板中调用ejs.render:
example.ejs 的内容:
<h1>Example EJS template<h1>
<p><%- ejs.render(data.includeCode,{data:data}) %><p>
带有 EJS 代码的 NodeJS/Express:
import ejs from "ejs";
globalThis.ejs = ejs; // make sure ejs is available in the global context
let includeCode = `<% if (data.dSwitch === 1) { %> 1 detected <% } else { %> Something else <% } %>`
let ejsdata = {...{includeCode: includeCode}, ...{dSwitch: 1}};
res.render("example.ejs",{data:ejsdata});
结果输出:
<h1>Example EJS template</h1>
<p> 1 detected </p>
有没有办法让包含的内容来自变量而不是来自文件?
我需要从数据库而不是文件中获取包含的内容,我想做这样的事情:
example.ejs 的内容:
<h1>Example EJS template<h1>
<p><%- include(data.includeCode) %><p>
带有 EJS 代码的 Nodejs/Express:
let includeCode = `<% if (data.dSwitch === 1) { %> 1 detected <% } else { %> Something else <% } %>`
let ejsdata = {...{includeCode: includeCode}, ...{dSwitch: 1}};
res.render("example.ejs",{data:ejsdata});
我想看到的是以下输出:
<h1>Example EJS template</h1>
<p> 1 detected </p>
我尝试使用 <%- data.includeCode %> 但输出为
<h1>Example EJS template</h1>
<p> <% if (data.dSwitch === 1) { %> 1 detected <% } else { %> Something else <% } %> </p>
解决方法是从ejs模板中调用ejs.render:
example.ejs 的内容:
<h1>Example EJS template<h1>
<p><%- ejs.render(data.includeCode,{data:data}) %><p>
带有 EJS 代码的 NodeJS/Express:
import ejs from "ejs";
globalThis.ejs = ejs; // make sure ejs is available in the global context
let includeCode = `<% if (data.dSwitch === 1) { %> 1 detected <% } else { %> Something else <% } %>`
let ejsdata = {...{includeCode: includeCode}, ...{dSwitch: 1}};
res.render("example.ejs",{data:ejsdata});
结果输出:
<h1>Example EJS template</h1>
<p> 1 detected </p>