kevinlelo
kevinlelo

Reputation: 51

How to make modular HTML pages (partials) using Node?

I've been trying to find a way to write HTML partials (header.html, nav.html etc.) and include them inside another HTML page as a part of my build process.

I know about server-side includes in Apache or includes in PHP but I was wondering if there was a way to do it in Node ? I've tried using template engines like Jade or Handlebars but they were not really built for that. Jade was the closest to what I'm trying to achieve but I don't want to use the syntax and there's no good way to use regular HTML. With every other one you have to include a script tag in your HTML, which I would have to strip for production.

I'm just trying to build a static website and would like to keep my build process simple (I'm using NPM scripts). Do you know any other way around copy-pasting the common parts of my website for every page ? How do you manage this in your workflow ?

Upvotes: 1

Views: 1155

Answers (2)

kevinlelo
kevinlelo

Reputation: 51

Here is a recap (a bit overdue) of what seem to be the best solutions for a simple use case: preprocess (has more options, can use custom or environment variables) and ssi (mentioned by @Alex K., it is very simple and sticks to Apache-style server-side includes). I ruled out jade since it added a lot of features I didn't really need.

Upvotes: 1

AkkarinZA
AkkarinZA

Reputation: 601

This actually is really a perfect use case for jade or some other tempting engine.

Layout

The basic approach would be to create a layout.jade file with all the stuff that doesn't change and dictates the general layout of the site.

layout.jade

doctype strict
html(xmlns='http://www.w3.org/1999/xhtml')
  head
    meta(http-equiv='Content-Type', content='text/html; charset=utf-8')
    title some title
  body
    | Static content like nav
    block pageContent

Content based on the route

Within the layout file you can define a series blocks as place holders for content to be injected from other templates. That template will extend the layout and inject the relevant blocks, something like this:

some-route-template.jade

extends layout

block pageContent
  | I am content from the relevant page

Compilation

The only thing left at this point is to compile template that matches the requested route using the jade library

Upvotes: 0

Related Questions