javascript - Node.js + Mustache to Preprocess Static HTML -



javascript - Node.js + Mustache to Preprocess Static HTML -

i'm working on project requires static html pages converted new static html pages. scraped pages cheerio content , stored relationships between pages json.

the challenge produce static html page table of contents interconnects everything.

mustache template:

<h1>table of contents</h1> {{#toc}} <h2>{{modulename}}</h2> <ul class='module'> {{#page}} <li><a href='{{url}}'>{{title}}</a></li> {{/page}} </ul> {{/toc}}

data:

{ "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 setup:

class="lang-js prettyprint-override">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); // loop through html files appending new menu using cheerio...

this append <h1>table of contents</h1>, nil else. must missing obvious, because can't create sense of this.

i'm new mustache programming in general, advice appreciated.

you read json file text string , need convert object before invoking mustache.render.

use json.parse:

'use strict'; var mustache = require("mustache"); var fs = require("fs"); var page = fs.readfilesync("page.mustache").tostring(); var info = json.parse(fs.readfilesync("data.json").tostring()); var h = mustache.render(page, data); console.log(h);

output:

<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>

in javascript, there 2 functions: json.parse , json.stringify.

json.parse -- returns object given json-text

json.stringify -- converts value json-notation.

javascript node.js mustache

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -