簡體   English   中英

NodeJs-如何在渲染的EJS中渲染EJS?

[英]NodeJs - How to render EJS in a rendered EJS?

那是我的主意:我想加載一個渲染的ejs文件作為我的主模板ejs文件的主體。 可能嗎?

我的app.js:

router.get('/', function(req, res) {
  res.render('layout', {title: "Example title", body: _____________});
});

我嘗試了以下操作,但沒有成功:

body: res.render('page1_body_content')

那將是我的主模板文件(layout.ejs)

 <!doctype html> <html> <head> <title> <% (title) ? title : '' %> </title> <link rel="stylesheet" href="https://v4-alpha.getbootstrap.com/dist/css/bootstrap.min.css"> <link rel="stylesheet" href="css/font-awesome-4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="css/style.css" /> </head> <body> <%= body %> </body> </html> 

我的第二個文件(page1_body_content.ejs)如下所示:

 <b>hallo</b> 

結果應如下所示:

 <!doctype html> <html> <head> <title> Expample title </title> <link rel="stylesheet" href="https://v4-alpha.getbootstrap.com/dist/css/bootstrap.min.css"> <link rel="stylesheet" href="css/font-awesome-4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="css/style.css" /> </head> <body> <b>Hallo</b> </body> </html> 

試試這個代碼:

var ejs = require('ejs');
var compiled = ejs.compile(fs.readFileSync(__dirname + '/page1_body_content.ejs', 'utf8'));
var html = compiled();

res.render('layout', {title: "Example title", body: html });

將正文標簽代碼更新為:-

<body>
    <%- body %>
</body>

暫無
暫無

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

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