Today, I want to present a simple way to use
purrr to create a static website generator. Of course, there is Jekyll, Hugo and the
blogdown package, but in many cases you may find yourself, like I did, with your own bits and pieces of html, no time to learn yet another language, and in need of a way to put all this into a structured and consistent static website.
The approach I took is
- keep all the website elements in one large html file, the “master page” (a collection of files works too)
- use html comments to define the start and end of the different sections, of which the different pages of the website will be composed
- define all links using hrefs on #ids
and write a
- manage the recombination of the sections onto different pages
- replace all href-attributes with correct link addresses
To show how this works, assume our “master page” looks like this
class="A"> AA - Intro material href="#DD"> LINK to DDid="BB">
class="B"> Section BB href="#CC"> LINK to CCid="CC">
class="C"> Section CC href="#BB"> LINK to BBid="DD">
This html contains all the parts we need to piece together our website. All we do here is to mark each of our sections with html-comments à la
. For simplicity, we also place and name our id-attributes accordingly. Also, usually, we would keep the CSS in a separate file.
Now, let’s say we want a front page with intro material A and one page each for the material in sections B and C+D.
We start by reading the file into a nested data frame, one nest for each of the sections we have defined
library(tidyverse) library(stringr) PATHOUT = "./Site/" fildat <- readLines("masterpage.html") ## marker for html blocks markerdat <- tibble( markerline = fildat %>% str_which("|\\t", "")) markerall <- markerdat %>% select( -orig ) %>% spread(key = markertype, value = markerline) %>% mutate(origlines = map2( START, END, ~`[`(fildat, .x:.y))) %>% arrange(START) markerall
## # A tibble: 6 x 4 ## markername END START origlines ##
## 1 HEADER 17 1
## 2 TOP 29 18 ## 3 AA 35 30 ## 4 BB 44 36 ## 5 CC 53 45 ## 6 DD 63 54
We then define how our website should be built by declaring the order of the building blocks for each page.
pagedef <- list( main = tibble( filename = "index.html", blocks = c("HEADER", "%MINIFYHTML52f57c6bc7ea6a195c6853c9c5fdc73d29%", "\"HOME\">", "TOP", "AA", "
A few additional remarks