[英]How to include html files with express and ejs
I want to make my webpage modular so that I don´t need to write my stuff again and again.我想让我的网页模块化,这样我就不需要一次又一次地写我的东西。 I thought my solution would be the ejs lib.
我以为我的解决方案是 ejs lib。 So I´ve using express and ejs that is configured like this:
所以我使用了配置如下的 express 和 ejs:
const app = express();
app.engine('.html', require('ejs').renderFile);
app.set('view engine', 'html');
app.set('views', __dirname + '/wwwroot/views');
My views folder struct looks like that:我的视图文件夹结构如下所示:
wwwroot
static
css
js
views
login
index.html
profile
dashboard.html
templates
inc_header.html
inc_footer.html
My Dashboard has the following content我的仪表盘有以下内容
<% include templates/inc_header.html %>
This is my dashboard
The Header file will not be included.头文件将不包括在内。 I´ve tried wwwroot/views/templates/header.html and header.html.
我试过 wwwroot/views/templates/header.html 和 header.html。 Nothing works.
什么都行不通。
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 %> This is my dashboard
<% include templates/inc_header.html %> 这是我的仪表板
Looks like the file will not be rendered?看起来文件不会被渲染?
<% - include templates/inc_header.html %> <% -包括模板/inc_header.html %>
add the hyphen to the include tag and it will work.将连字符添加到包含标记中,它将起作用。
you can also send data to the file being included您还可以将数据发送到包含的文件
<%- include("../partials/head.ejs", {variant:e.name}); %>
but NB: if a variable is to be used in it, it has to be passed to it from anywhere it is being included.但注意:如果要在其中使用变量,则必须从包含它的任何地方将其传递给它。
to solve this issue you can set a default value to it if not sent Add this to the file being included要解决此问题,您可以为其设置默认值(如果未发送)将其添加到所包含的文件中
<em>Variant: <%= typeof variant != 'undefined' ? variant : 'default' %></em>
for more check out this link有关更多信息,请查看此链接
for using html files in express using ejs, use this in the index.js(entry point for tour application)要使用 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.