![](/img/trans.png)
[英]How to include js files in my EJS templates in node.js using express 3.x
[英]How to include html files with express and ejs
我想让我的网页模块化,这样我就不需要一次又一次地写我的东西。 我以为我的解决方案是 ejs lib。 所以我使用了配置如下的 express 和 ejs:
const app = express();
app.engine('.html', require('ejs').renderFile);
app.set('view engine', 'html');
app.set('views', __dirname + '/wwwroot/views');
我的视图文件夹结构如下所示:
wwwroot
static
css
js
views
login
index.html
profile
dashboard.html
templates
inc_header.html
inc_footer.html
我的仪表盘有以下内容
<% include templates/inc_header.html %>
This is my dashboard
头文件将不包括在内。 我试过 wwwroot/views/templates/header.html 和 header.html。 什么都行不通。
app.engine('.html', require('ejs').renderFile);
app.set('view engine', 'html');
app.set('views', __dirname + '/wwwroot/views');
app.use(session({
secret: program.secret || "secret",
resave: true,
saveUninitialized: true
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }))
app.use('/', express.static(path.join(__dirname, '/wwwroot/static/')));
<% include templates/inc_header.html %> 这是我的仪表板
看起来文件不会被渲染?
<% -包括模板/inc_header.html %>
将连字符添加到包含标记中,它将起作用。
您还可以将数据发送到包含的文件
<%- include("../partials/head.ejs", {variant:e.name}); %>
但注意:如果要在其中使用变量,则必须从包含它的任何地方将其传递给它。
要解决此问题,您可以为其设置默认值(如果未发送)将其添加到所包含的文件中
<em>Variant: <%= typeof variant != 'undefined' ? variant : 'default' %></em>
有关更多信息,请查看此链接
要使用 ejs 在 express 中使用 html 文件,请在 index.js(游览应用程序的入口点)中使用它
const app = express();
app.engine('.html', require('ejs').renderFile);
app.set('view engine', 'html');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.