我正在尝试在我的快递应用中加载ejs模板。我将'view engine'设置为ejs,并将ejs模板传递给response.render。但是,当我导航到localhost:8000时,我只看到文字形式的include语句。
模板文件: index.ejs
{% include('commonheader') %}
<div id='mainbody' class='container-fluid'>
<nav>
{%- include('mainheader', {
navbar: navbar_options
}) %}
</nav>
</div>
{%- include('commonfooter', {
footer: sitemap
}) %}
commonheader.ejs
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<title><%= title %></title>
<!-- bootstrap -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
<!-- bootstrap js -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
crossorigin="anonymous"></script>
<!-- Jquery -->
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<!-- Custom stylesheets and js -->
<%- if(stylesheets){
if(typeof stylesheets == []){
Array.prototype.forEach(function(sheet){
%}<link rel='stylesheet' href= {%= sheet %}>{%
}, stylesheets);
}
else{
%}<link rel='stylesheet' href= {%= Array.prototype.shift.call(stylesheets) %}>{%;
}
}; %}
</head>
<body>
commonfooter.ejs
<footer>
<% if(footer){
for(let k in footer){
if(typeof footer[k] []){
Array.prototype.forEach.call(function(link){
%}<a href= {%= link['href'] %}>
<li>{%= link['name'] %}</li>
</a>{%
});
}
else{
%}<a href= {%= link['href'] %}>
<ul>{%= link['name'] %}</ul>{%
}
}
%}
</footer>
</body>
</html>
routes.js
const express = require('express');
const path = require('path');
const appinst = express();
const _template_dir = '/static';
const _root_addr = '127.0.0.1:8000';
// bind render engine to ejs
appinst.set('views', path.join(__dirname,'views'));
appinst.set('view engine', 'ejs');
appinst.get('/', function(request, response){
response.render('index', {
css_stylesheets: [
'css/index.css',
],
navbar_options: [
{
'href': _root_addr + '/',
'name': 'Home'
},
{
'href': _root_addr + '/create',
'name': 'Create'
},
{
'href': _root_addr + '/howto',
'name': 'How To'
}
],
sitemap: [
{
'href': _root_addr + '/',
'name': 'Home'
},
{
'href': _root_addr + '/aboutus',
'name': 'About Us'
},
{
'href': _root_addr + '/create',
'name': 'Create'
},
{
'href': _root_addr + '/howto',
'name': 'How To'
},
{
'href': _root_addr + '/contactus',
'name': 'Contact Us'
}
]
});
});
浏览器输出:
{% include('commonheader') %}
{%- include('mainheader', { navbar: navbar_options }) %}
{%- include('commonfooter', { footer: sitemap }) %}
答案 0 :(得分:0)
我认为您错误输入了包含内容,应该如下所示:
<%- include('mainheader', { navbar: navbar_options }); %>
但是您的代码中缺少开始和结束标记<%-
%>
您仅使用%-
和%
{%- include('mainheader', { navbar: navbar_options }) %}