簡體   English   中英

Node.js +胡子預處理靜態HTML

[英]Node.js + Mustache to Preprocess Static HTML

我正在一個需要將靜態HTML頁面轉換為新的靜態HTML頁面的項目中。 我用Cheerio抓取了頁面內容,並將頁面之​​間的關系存儲為JSON。

面臨的挑戰是如何生成一個包含將所有內容互連的目錄的靜態html頁面。

小胡子模板:

<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"
        }]
    }]
}

節點設置:

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> ,但僅此而已。 我一定會錯過一些非常明顯的東西,因為我無法理解這一點。

我對小胡子和編程一般都是新手,因此我們將不勝感激。

您從文件中讀取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表示法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM