Html 无法使用 EJS 正确呈现

时间:2021-02-03 19:10:36

标签: node.js ejs

我使用的是 vanilla node.js。我有以下代码,它应该从在 /views 文件夹

中保存为 .ejs 文件的模板呈现一个 html 页面
const handleGetRequest = (req, res) => {
  const { url } = req;
  let templatePath = '/views/';
  switch (url) {
    case '/': templatePath += 'index.ejs'; break;
    case '/about': templatePath += 'aboute.ejs'; break;
    case '/posts': templatePath += 'blog/posts.ejs'; break;
    case '/posts/post': templatePath += 'blog/post.ejs'; break; 
    case '/posts/create': templatePath += 'blog/create.ejs'; break; 
  }
  const htmlContent = fs.readFileSync(__dirname + templatePath, 'utf-8');
  const renderedHTML = ejs.render(htmlContent, templatePath, {title: 'sometitle'});
  console.log(renderedHTML);


  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write(renderedHTML);
  res.end();
};

但它没有正确呈现它们,在控制台中,我得到如下呈现的输出

false


<div class="container-lg">
  <h2>The most recent posts</h2>
  <div class="post">
      <a class="post-link"></a>
  </div>

</div>

false

这是我的模板文件(应该没有太多逻辑)

<%- includes('/partials/head') %>

<div class="container-lg">
  <h2>The most recent posts</h2>
  <div class="post">
      <a class="post-link"></a>
  </div>
  
</div>

<%- includes('/partials/bottom') %>

还有部分...

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
    <title><%= title %></title>
  </head>
  <body>
</body>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>
</html>

0 个答案:

没有答案