我正在尝试将EJS作为视图引擎与Express一起使用。我的layout.ejs好像没有用过。我在“views”文件夹中有两个视图index.ejs和layout.ejs。似乎呈现了index.js,但没有呈现layout.ejs。layout.ejs文件应该包含一个CSS文件,但是当页面在浏览器中呈现时,就不存在了。我放在layout.ejs文件中的任何测试文本都不会随响应一起输出。
我是否遗漏了一个额外的配置步骤?
谢谢!
我的server.js代码:
var express = require('express');
var app = express();
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res){
res.render('index.ejs', {title: 'EJS Engine'});
});
app.listen(8080);在我的layout.ejs中,我链接到一个驻留在公用文件夹中的css文件。
layout.ejs:
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<%- body %>
</body>
</html> index.ejs
<div id="container">
index.html
</div>发布于 2014-03-03 07:38:59
这是您需要的模块:https://www.npmjs.org/package/express-ejs-layouts
执行以下操作:
npm install express-ejs-layouts // install the layout module from the command line
var express = require("express")
,path = require('path')
,fs = require('fs')
,expressLayouts=require("express-ejs-layouts") // add this requirement
, app = express();
app.use(express.bodyParser());
app.use(expressLayouts); // add this use()
app.use(express.static(__dirname));现在,ejs引擎应该使用您的布局了。
发布于 2014-03-09 11:42:01
app.set('view options', { layout:'layout.ejs' });将layout.ejs放入视图文件夹中。或者,您也可以将layout.ejs放置在视图/布局文件夹中,然后使用
app.set('view options', { layout:'layouts/layout.ejs' });发布于 2013-10-13 03:25:03
我也有类似的问题。在我的例子中,我更愿意使用Jade,但是我需要一个更"html“风格的模板引擎来支持特定的项目。一开始,我考虑使用express-partials或ejs-locals ( Jonathan Lonowski在评论中提到),甚至在Jade模板中通过管道或点语法使用html (有关该选项的更多信息,请参阅here和this,因此post)。我不能在这个项目中引入express-partials和ejs-locals的额外依赖项。这两个项目看起来确实不错,可能会满足您的需求。
如果您不想使用这些项目,可以执行以下操作:
视图/布局-head.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>The title</title>
</head>
<body>视图/布局-Foot.ejs
</body>
</html>views/index.ejs (或任何其他页面)
<% include layout-head %>
This is the index page - <%= title %>
<% include layout-foot %>routes/index.js
exports.index = function(req, res){
res.render('index', { title: 'Express' });
}这不是一个最佳的解决方案,但它是有效的。我的大部分应用程序将是一个单页面的应用程序,我有一些其他的限制,我必须工作,所以这是我的需要。在许多情况下,这可能不是最好的解决方案-特别是当您有复杂的和/或更改布局的时候。
https://stackoverflow.com/questions/15036904
复制相似问题