首页 > 解决方案 > ejs:找不到包含包含文件

问题描述

我是一名学生,正在做一个项目。我正在尝试从服务器获取书籍列表并使用 ejs 将它们一一显示。

项目结构:

 |
 |-----routes
 |       |-----index.js
 |-----views
 |       |
 |       |----catalogue.ejs
 |       |----partials
 |       |      |----card.ejs
 |       |

index.js:

var express = require('express');
var router = express.Router();
router.get('/catalogue', function(req, res, next) {
  let books = [{ bookName: 'The Way of Kings',                  author: 'Brandon Sanderson',    price: 19.90,   id: '01' },
               { bookName: 'Words of Radiance',                 author: 'Brandon Sanderson',    price: 19.90,   id: '02' },
               { bookName: 'Oathbringer',                       author: 'Brandon Sanderson',    price: 19.90,   id: '03' },
               { bookName: '100 Paper Planes to fold & fly',    author: 'Usborne',              price: 13.90,   id: '04' },
               { bookName: 'Brain Games for Cleaver Kids',      author: 'Usborne',              price: 10.90,   id: '05' },
               { bookName: 'This is Going To Hurt',             author: 'Adam Kay',             price: 15.90,   id: '06' },
               { bookName: 'Normal People',                     author: 'Sally Ronney',         price: 10.90,   id: '07' },
               { bookName: 'Fahrenheit 451',                    author: 'Ray Bradbury',         price: 10.90,   id: '08' },
               { bookName: 'To be taught if fortunate',         author: 'Becky Chambers',       price: 9.90,    id: '09' },
               { bookName: 'The Better Sister',                 author: 'Alafer Burke',         price: 15.90,   id: '10' },
               { bookName: 'Crooked Kingdom',                   author: 'Leigh Bardugo',        price: 10.90,   id: '11' }
               ];

  res.render('catalogue', { books: books, page:'Catalogue', menuId:'catalogue'});
});

目录.ejs:

<!doctype html>
<html lang="en">
<head>
    <%- include partials/head %>
    <link rel="stylesheet" href="../../public/stylesheets/style.css">
</head>
<body>
<header>
    <%- include partials/header %>
</header>
<%- include partials/menu %>

<% books.forEach(function(book) { %>
    <%- include ('partials/card',{book:book}) %>
<% }); %>

<div class="container-fluid bg-3 text-center">
    <h3><%= page %></h3>
    <br>
</div>

<footer>
    <%- include partials/footer %>
</footer>

</body>
<%- include partials/script %>
</html>

卡.ejs:

<main class="card container">
    <div class="card">
        <p class="bookName"><%= book.bookName %></p>
        <p class="author"><%= book.author %></p>
        <p class="price">Price: <%= book.price %>$</p>
        <p><button>Add to Cart</button></p>
    </div>
</main>

当我像这样运行它时,它只显示错误:找不到包含包含文件。我从 ejs 文档中复制了循环模板,所以我不明白为什么它不起作用。

我试着绕开它看看问题出在哪里,我意识到当我只包含部分/卡片而不是目录中的循环时,它可以工作。但是,如果我尝试添加任何内容,甚至像:include (partials/card) 这样的父代,它都会给我错误。什么可能导致这个?

感谢任何试图提供帮助的人,我有一个截止日期。

标签: javascriptnode.jsexpressejs

解决方案


你应该使用

<%- include partials/header %> 

不是

<% include partials/header %>

<%- 应该用于包含文件


推荐阅读