在添加if语句之前,一切正常。
但是添加了if语句后,我发现EJS没有呈现它。
app.js
const express = require('express');
const http = require('http');
const app = express();
const session = require('express-session');
const server = http.createServer(app);
const routes = require('./routes');
app.use(express.static(__dirname + '/public'));
app.use('/', routes);
routes.js
const express = require('express');
const routes = express.Router();
const fs = require('fs');
const ejs = require('ejs');
var index = fs.readFileSync(__dirname + '/pages/index.ejs', 'utf-8');
var head = fs.readFileSync(__dirname + '/pages/head.ejs', 'utf-8');
var nav = fs.readFileSync(__dirname + '/pages/nav.ejs', 'utf-8');
var partials = {head, nav}
routes.get('/', function(req, res) {
var data = ejs.render(index, partials);
res.send(data);
});
index.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<%- head %>
<title>QA Engine Index</title>
</head>
<body id="page-top">
<%- nav %>
nav.ejs(部分)
<% if (true) { %>
<ul class="navbar-nav ml-auto ml-md-0 btn-toolbar" role="btn-toolbar">
<button onclick="location.href='/register'" type="button" class="navbar-btn ml-md-0 btn btn-primary mr-2">Register</button>
<button onclick="location.href='/login'" type="button" class="navbar-btn ml-md-0 btn btn-primary mr-2">Login</button>
</ul>
<% } else { %>
<% } %>
图片是添加if语句后导航栏的外观。
我添加了
nav = ejs.render(nav);
并解决了问题。
问题是nav.ejs在我使用它呈现其他页面之前未呈现。