javascript - Node.js + Mustache 预处理静态 HTML

标签 javascript node.js mustache

我正在开发一个项目,需要将静态 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.parseJSON.stringify .

JSON.parse -- 返回给定 JSON 文本的对象

JSON.stringify -- 将值转换为 JSON 表示法。

关于javascript - Node.js + Mustache 预处理静态 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26262890/

相关文章:

javascript - 了解 JavaScript 中的闭包范围

Azure Bot 中的 JavaScript 变量分配

javascript - 是否可以停止当前正在执行的 Javascript 代码?

java - 模板框架基准测试

javascript - 将 javascript 应用到 Mustache 创建的对象

javascript - $scope 值未显示在其他 Controller 中,如何设置标记

javascript - 使用 Mongoose 保存

node.js - Intellij 可以与 Visual-Studio-Code 样式的 docker devcontainer 一起使用吗?

node.js - 在 Electron 中使用sqlite3,db.serialize不能正常工作

python - 如果未定义模式,pystache 可以告诉我吗?