我想出了一种相当粗糙的方法来处理HTML模板。类似于PHP<?php include("navigation.html"); ?>
server.js
var fs = require('fs');
String.prototype.filter = function(search,replace){
var regex = new RegExp("{{" + search.toUpperCase() + "}}","ig");
return this.replace(regex,replace);
}
var navigation = fs.readFileSync(__dirname + "/parts/navigation.html");
function preProcessPage(html){
return html.filter("nav",navigation);
}
var express = require('express');
var app = express();
// Keep your server directory safe.
app.use(express.static(__dirname + '/public/'));
// Sorta a server-side .htaccess call I suppose.
app.get("/page_name/",function(req,res){
var html = fs.readFileSync(__dirname + "/pages/page_name.html");
res.send(preProcessPage(html));
});
page_name.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>NodeJS Templated Page</title>
<link rel="stylesheet" type="text/css" href="/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="/css/font-awesome.min.css">
<!-- Scripts Load After Page -->
<script type="text/javascript" src="/js/jquery.min.js"></script>
<script type="text/javascript" src="/js/tether.min.js"></script>
<script type="text/javascript" src="/js/bootstrap.min.js"></script>
</head>
<body>
{{NAV}}
<!-- Page Specific Content Below Here-->
</body>
</html>
navigation.html
<nav></nav>
载入页面结果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>NodeJS Templated Page</title>
<link rel="stylesheet" type="text/css" href="/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="/css/font-awesome.min.css">
<!-- Scripts Load After Page -->
<script type="text/javascript" src="/js/jquery.min.js"></script>
<script type="text/javascript" src="/js/tether.min.js"></script>
<script type="text/javascript" src="/js/bootstrap.min.js"></script>
</head>
<body>
<nav></nav>
<!-- Page Specific Content Below Here-->
</body>
</html>
require
,在Windows的同一目录中有一个文件夹。您必须使用Unix风格的寻址:./mydir
而不是普通的oldmydir
。