簡體   English   中英

有沒有辦法在 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});

我想看到的是以下 output:

<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});

結果 Output:

<h1>Example EJS template</h1>
<p> 1 detected </p>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM