ฉันได้วิธีที่ค่อนข้างหยาบในการจัดการสิ่งนี้สำหรับเทมเพลต 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 คุณได้มีการใช้ยูนิกซ์สไตล์ที่อยู่: แทนธรรมดาเก่า./mydir
mydir