[英]How can I have my index.htm file include other html files
使用节点。
这是我从服务器提供服务的方式:
app.get('/', function(req, res) {
res.sendfile('./views/index.html');
});
在这个index.html文件中,我需要提供两个文件:
head.htm
和body.htm
。
在PHP中,我只会使用include。 如何在Node中完成?
这里有许多解决方案……这取决于您偏爱使用哪种工具的个人偏好。
我使用过的一种这样的工具是EJS。 你可以在这里读到所有和它有关的:
https://code.google.com/archive/p/embeddedjavascript/wikis/Templates.wiki
编辑:这样的一个示例是具有页眉和页脚模板,以及包含它们的index.ejs页面。 (尽管您可以在要呈现的索引页中的任何位置使用这些文件)。
Index.ejs(ejs只是使用的扩展名,与其中带有呈现标记的html相同):
<% include templates/header %>
<h1> Index page!</h1>
<% include templates/footer %>
Header.ejs:
<html>
<head>
</head>
<body>
Footer.ejs:
</body>
</html>
内部路由配置:
app.get("/", function(req, res){
res.render("index");
}
很明显,您需要执行一些配置要求,我还假设您使用的是Express,EJS可以很轻松地使用Express。
如果您提到您正在使用的模板引擎,这将有所帮助。 默认情况下,它应该是Pug(或Jade)(如果您使用的是我认为的Express Generator)。
对于玉:
app.js:
var express = require('express');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// define routes
app.get('/', function(req, res) {
res.render('index.html');
});
现在,默认情况下,views文件夹将用于提供文件。 一个好的做法是创建一个主布局,该布局定义HTML文件的常规结构,然后在扩展文件中添加特定的内容。
master.pug:
doctype html
html
head
title
block title // title block
link(rel='stylesheet', href='/stylesheets/default.css') //some default styles
block styles // block for more styles
body
include header.pug //include header file
block content // block to insert contents
script(type='text/javascript',src='/javascripts/faculty-index.js') // default scripts
block scripts // block to insert scripts
include footer.pug // include footer file
块定义了一个空间,您可以在扩展文件后输入内容。 Include基本上只包括该空间中文件中的代码。 现在你是index.pug可能是这样的
index.pug
extends master.pug // extend the base template
block title
| Index Page // adds the content in the title block
block styles
link(rel='stylesheet', href='/stylesheets/index.css') // specific styles for index
block content
h1 This is the index // adds the index content which goes in the body tag where content is defined
在这里,索引文件使用主文件中的所有内容,并在标题,正文和样式中添加其自己的内容。
查看pug文档以了解更多信息
任何模板引擎都可以复制类似的行为。 我使用过的另一个是Handlebars ,我喜欢它,因为它的语法更像是编写html。 但是,您必须先进行设置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.