我正在开发一个项目,需要将静态 HTML 页面转换为新的静态 HTML 页面。我使用 Cheerio 抓取页面内容并将页面之间的关系存储为 JSON。
挑战在于生成一个静态 html 页面,其中包含互连所有内容的目录。
mustache 模板:
<h1>Table of Contents</h1>
{{#toc}}
<h2>{{moduleName}}</h2>
<ul class='module'>
{{#page}}
<li><a href='{{url}}'>{{title}}</a></li>
{{/page}}
</ul>
{{/toc}}
数据:
{
"toc": [{
"moduleName": "Getting Started",
"page": [{
"title": "Welcome",
"url": "L0-01_Welcome.html"
}, {
"title": "Who Should Read This?",
"url": "L0-02_WhoFor.html"
}]
}, {
"moduleName": "Module 1",
"page": [{
"title": "Definitions",
"url": "L1-01_Definitions.html"
}]
}]
}
Node 设置:
var Mustache = require("mustache");
var fs = require("fs");
var cheerio = require("cheerio");
// File Paths
var pathToMustache = "./templates/toc.mustache";
var pathToJSON = "./menu/data.json";
// Generate HTML menu
//var htmlMenu = Mustache.render(fs.readFileSync(pathToMustache).toString(), fs.readFileSync(pathToJSON));
var htmlMenu = Mustache.to_html(fs.readFileSync(pathToMustache).toString(), fs.readFileSync(pathToJSON));
console.log(htmlMenu);
// Then loop through the html files appending the new menu using Cheerio...
这确实成功附加 <h1>Table of Contents</h1>
, 但没有别的。我一定错过了一些非常明显的东西,因为我无法理解这一点。
我对 mustache 和一般编程都很陌生,因此非常感谢您的建议。
最佳答案
您从文件中读取 JSON 作为文本字符串,需要在调用 Mustache.render 之前将其转换为对象。
使用JSON.parse
:
'use strict';
var Mustache = require("mustache");
var fs = require("fs");
var page = fs.readFileSync("page.mustache").toString();
var data = JSON.parse(fs.readFileSync("data.json").toString());
var h = Mustache.render(page, data);
console.log(h);
输出:
<h1>Table of Contents</h1>
<h2>Getting Started</h2>
<ul class='module'>
<li><a href='L0-01_Welcome.html'>Welcome</a></li>
<li><a href='L0-02_WhoFor.html'>Who Should Read This?</a></li>
</ul>
<h2>Module 1</h2>
<ul class='module'>
<li><a href='L1-01_Definitions.html'>Definitions</a></li>
</ul>
在 JavaScript 中,基本上有两个函数: JSON.parse和 JSON.stringify .
JSON.parse
-- 返回给定 JSON 文本的对象
JSON.stringify
-- 将值转换为 JSON 表示法。
关于javascript - Node.js + Mustache 预处理静态 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26262890/