Quarto
Best practices
R

Content as data: a series registry for a Quarto blog

Automate series navigation, cross-references, and planned content using a YAML registry, a Pandoc Lua filter, and unit test validation

Model series and related posts as structured data with a YAML registry and a Pandoc Lua filter, guarded by testthat so missing references fail in CI.
Published

2026-09-27

Modified

2026-11-13

The problem

As a technical publication grows, articles rarely stand alone: tutorials form sequential tracks, practical guides build on setups, and standalone articles cross-reference deeper dives.

Managing these relationships manually in markdown leads to two failure modes:

  1. Stale cross-references. Numbered directories (topics/01-setup) break when inserting intermediate articles. Switching to flat semantic slugs (posts/setup/) solves URLs, but hand-written “See also” lists decay as slugs change or series are reorganised.
  2. Planned content has nowhere to live. Roadmaps include planned series that are not yet written. In a file-driven site, planned topics remain invisible, or links to pages that do not yet exist return 404 errors.

To scale cleanly, content relationships must be managed as structured data.

The web-repo way

Static-site generators decouple content structure from presentation using data files and schemas:

  • Hugo (Related Content): configured under related in the site configuration, with weighted indices on front matter such as tags, dates or heading fragments, and a score threshold. Templates call .Site.RegularPages.Related . to get a ranked list.
  • Jekyll (site.related_posts): up to ten related posts, which by default are simply the ten most recent. Better matches need the --lsi option (latent semantic indexing), which requires the classifier-reborn plugin; GitHub Pages does not support it.
  • Astro (content collections): collections are defined in src/content.config.ts, with an optional schema that validates each entry. In a schema, reference() declares a property as an entry from another collection, which templates then query with getEntry() or getEntries().
  • Eleventy (_data/): files in the global data folder are available to every template under their file name, so shared data lives apart from the pages.

Across these frameworks, the pattern is consistent: declare relationships in structured data files and let the generator assemble navigation components.

The R way: Content as data in Quarto

This blog uses the content-as-data pattern to automate navigation across all series and articles. In Quarto, we implement this with four coordinated components:

  1. A YAML series registry (_data/series.yml) declaring all series, tracks, and overarching relationships.
  2. Front matter in posts defining series membership and curated related posts.
  3. A Pandoc Lua filter (_filters/related.lua) that executes during rendering to build navigation cards.
  4. A {testthat} validation test (tests/testthat/test-site-series-registry.R) that catches broken references in CI.

1 · The series registry

The registry file _data/series.yml acts as the single source of truth for all tracks:

series:
  - id: basics
    status: live
    track: engineering
    related:
      - {to: testing, type: read-next, note: "Tests build on foundations."}

  - id: testing
    status: live
    track: engineering
    related:
      - {to: basics, type: read-first, note: "Package and repo setup."}
      - {to: reporting, type: see-also, note: "Testing reporting outputs."}

  - id: reporting
    status: planned
    track: pharma
    title: "Clinical Reporting in R"
    summary: "Tables, listings and figures for clinical studies in R."
    related:
      - {to: testing, type: builds-on}

Every series defines an identifier, status (live or planned), track, and typed links. Live series pull their title and summary directly from their overview page (series/<id>.qmd), avoiding duplicated copy. Planned series carry titles and summaries in YAML, presenting a clear roadmap without dead links.

2 · Post front matter

Individual posts reference their series and declare hand-picked cross-references:

---
title: "Writing robust unit tests with testthat"
date: 2026-09-27
series: testing
order: 1
categories: ["R", "Best practices"]
related:
  - {post: project-structure, type: read-first}
  - {post: property-based-testing, type: read-next}
---

Posts in a series specify series: <id>, a sequential order: <n>, and up to three curated related: entries. Standalone posts (such as this article) omit series: and order:: they receive related cards, but no series header.

3 · The Pandoc Lua filter

The filter is listed under filters: in _quarto.yml, so Quarto runs it on every page. It reads the registry and the front matter of every post, works out what the current page needs, and appends Pandoc elements to the end of the page:

-- Simplified from the filter this blog uses. `plain()` turns Pandoc metadata
-- into Lua strings and tables; `load_site()` reads the registry and, with
-- pandoc.system.list_directory(), the front matter of every post.

-- The front matter of a .qmd file (or a whole .yml file) as Lua values.
local function read_yaml(path, whole_file)
  local f = io.open(path, "r")
  if not f then return nil end
  local text = f:read("a")
  f:close()
  local pattern = "^%-%-%-\r?\n(.-)\r?\n%-%-%-"
  local yaml = whole_file and text or text:match(pattern)
  if not yaml then return {} end
  return plain(
    pandoc.read("---\n" .. yaml .. "\n---\n", "markdown").meta
  )
end

-- A card is a Pandoc Link to a .qmd file, so Quarto resolves the URL.
local function card(href, label, title, body)
  return pandoc.Link({
    pandoc.Span(label, { class = "eyebrow" }),
    pandoc.Span(title, { class = "card-title" }),
    pandoc.Span(body or "", { class = "card-body" }),
  }, href, "", { class = "related-card" })
end

function Pandoc(doc)
  if not quarto.doc.is_format("html") then return doc end
  local rel = pandoc.path.make_relative(
    quarto.doc.input_file,
    quarto.project.directory
  )
  local pattern = "^posts/([^/]+)/index%.qmd$"
  local slug = rel:match(pattern)
  if slug then
    local series, posts = load_site()
    for _, block in ipairs(post_blocks(slug, series, posts)) do
      doc.blocks:insert(block)   -- series nav, then "Keep reading" cards
    end
  end
  return doc
end

Because the filter emits native Pandoc Link elements targeting .qmd files, Quarto resolves them to final URLs, allowing offline link checkers to verify them automatically.

Design decisions and lessons learned

Refining this system surfaced several practical engineering lessons:

3 · Why a Lua filter rather than R in CI

Our site keeps one rule: rendering needs no R. The render job in CI installs Quarto, which bundles Pandoc, but not R.

We considered two alternatives: - An R script generating JSON: An R script could parse front matter with {yaml} and output a committed JSON file. However, this requires committing generated artifacts and enforcing freshness tests in CI. - Client-side JavaScript over search.json: the browser could build the cards from Quarto’s search index. But the cards would exist only after JavaScript runs, not in the HTML, so neither readers without JavaScript nor a link checker would see them.

A Lua filter runs inside Quarto with nothing extra to install, and the cards are part of the rendered HTML.

4 · Gotcha: Listing placement and container IDs

When adding cards to series landing pages, we ran into an unexpected layout issue. Quarto’s listings documentation explains that listings are appended to the page by default; a div whose id matches the listing’s id controls where one appears.

The trap is which id. In our tests with Quarto 1.8.27, a listing without an explicit id looks for a div with the id listing, while the rendered listing container gets id="listing-listing". We first added a div with the container’s id, and Quarto ignored it. Without the right div, the listing is appended after everything else on the page, so it landed below the cards our filter had added.

The filter now checks for a div with the id listing and, if there isn’t one, inserts pandoc.Div({}, { id = "listing" }) before its cards. Giving each listing an explicit id and placing the div by hand works too; the filter just means no page has to remember.

The testthat safety net

Our filter skips anything it can’t resolve, so a typo never breaks the build. The cost: if an author mistypes a slug in related:, the card quietly disappears.

Silent omission creates a subtle failure mode: 1. A mistyped slug drops the card from rendering. 2. Because the link never renders into HTML, an offline link checker cannot detect a 404 error. 3. The broken recommendation remains unnoticed in production.

To prevent this, we write a {testthat} validation test. R developers routinely write tests for data frames and analysis pipelines; using {testthat} to validate publishing metadata is a natural extension:

library(testthat)

# Front matter from two posts, as yaml::yaml.load() returns it
posts <- list(
  intro = list(
    series = "basics",
    order = 1L,
    related = list(list(post = "setup", type = "read-first"))
  ),
  setup = list(related = list(list(post = "intro", type = "read-next")))
)
link_types <- c("read-first", "read-next", "builds-on", "see-also")

test_that("every related link resolves", {
  for (slug in names(posts)) {
    for (r in posts[[slug]]$related) {
      expect_true(r$post %in% names(posts), label = paste(slug, "->", r$post))
      expect_false(identical(r$post, slug), label = paste(slug, "self-link"))
      expect_true(r$type %in% link_types, label = paste(slug, r$type))
    }
  }
})

The real test also checks the registry, and that live series match their pages and the navbar. To check that it works, we broke the site’s data on purpose in four ways: - An unknown series link (to: phantom-series). - A broken post slug (post: missing-slug). - An invalid relationship type (type: deep-dive). - A duplicate order index (order: 1 assigned twice in the same series).

Each one failed the test. The same test runs in CI, so a typo fails the pull request instead of reaching readers.

What is next

Treating content relationships as structured data lays the groundwork for planned enhancements:

  • Learning paths: Curating cross-series reading paths for specific roles (such as onboarding clinical programmers).
  • Visual series maps: Rendering dependency graphs that illustrate how foundational practices lead to advanced workflows.
  • Track-grouped navigation: Organizing top-level navigation dropdowns by track as the library of series expands.

Companion code

View check-registry.R · Download

The standalone validator uses base R and {yaml}. It exposes read_registry(), read_front_matter(), scan_posts(), and check_registry(). Run the downloaded file with Rscript check-registry.R from the directory where you saved it. Its demo builds a tiny site with a broken post slug and prints the problem; the tests also cover a clean site and the four planted error types.

# Validates a Quarto series registry and post front matter.
# Checks that series IDs, post slugs, link types, and series ordering
# resolve without broken references or gaps.
#
# Run the downloaded file from the directory where you saved it:
#   Rscript check-registry.R

read_registry <- function(path) {
  if (!file.exists(path)) {
    stop(sprintf("Registry file '%s' does not exist.", path), call. = FALSE)
  }
  data <- yaml::read_yaml(path)
  if (is.list(data) && !is.null(data$series)) {
    data$series
  } else if (is.list(data)) {
    data
  } else {
    list()
  }
}

read_front_matter <- function(path) {
  if (!file.exists(path)) {
    return(list())
  }
  lines <- readLines(path, warn = FALSE)
  fences <- which(lines == "---")
  if (length(fences) < 2) {
    return(list())
  }
  yaml_text <- paste(lines[(fences[1] + 1):(fences[2] - 1)], collapse = "\n")
  parsed <- yaml::yaml.load(yaml_text)
  if (is.list(parsed)) parsed else list()
}

scan_posts <- function(dir) {
  if (!dir.exists(dir)) {
    return(list())
  }
  slugs <- list.files(dir)
  slugs <- slugs[dir.exists(file.path(dir, slugs))]
  post_files <- file.path(dir, slugs, "index.qmd")
  valid <- file.exists(post_files)
  slugs <- slugs[valid]
  post_files <- post_files[valid]
  stats::setNames(
    lapply(post_files, read_front_matter),
    slugs
  )
}

check_registry <- function(
  registry,
  posts,
  allowed_types = c("read-first", "read-next", "builds-on", "see-also")
) {
  problems <- list()

  record <- function(scope, item, problem) {
    problems[[length(problems) + 1L]] <<- list(
      scope = scope,
      item = item,
      problem = problem
    )
  }

  series_ids <- vapply(
    registry,
    function(s) if (!is.null(s$id)) as.character(s$id) else "",
    character(1)
  )

  # Check for duplicate series IDs
  dup_ids <- series_ids[nzchar(series_ids) & duplicated(series_ids)]
  for (dup in unique(dup_ids)) {
    record("registry", dup, sprintf("Duplicate series id '%s'", dup))
  }

  # Validate each series in registry
  for (s in registry) {
    sid <- s$id %||% "<unnamed>"
    if (!is.null(s$status) && !s$status %in% c("live", "planned")) {
      record(
        "registry",
        sid,
        sprintf("Invalid status '%s' in series '%s'", s$status, sid)
      )
    }
    if (identical(s$status, "planned")) {
      if (is.null(s$title) || !nzchar(as.character(s$title))) {
        record(
          "registry",
          sid,
          sprintf("Planned series '%s' is missing a title", sid)
        )
      }
      if (is.null(s$summary) || !nzchar(as.character(s$summary))) {
        record(
          "registry",
          sid,
          sprintf("Planned series '%s' is missing a summary", sid)
        )
      }
    }
    for (edge in s$related) {
      target <- edge$to %||% "<empty>"
      if (!target %in% series_ids) {
        record(
          "registry",
          sid,
          sprintf("Unknown series link: '%s' references '%s'", sid, target)
        )
      }
      if (identical(target, s$id)) {
        record(
          "registry",
          sid,
          sprintf("Series '%s' has a self-link", sid)
        )
      }
      link_type <- edge$type %||% "<missing>"
      if (!link_type %in% allowed_types) {
        record(
          "registry",
          sid,
          sprintf("Invalid link type '%s' in series '%s'", link_type, sid)
        )
      }
    }
  }

  # Live series IDs
  live_series <- vapply(
    Filter(function(s) identical(s$status, "live"), registry),
    function(s) as.character(s$id),
    character(1)
  )

  post_slugs <- names(posts)

  # Validate each post
  for (slug in post_slugs) {
    p <- posts[[slug]]
    if (!is.null(p$series)) {
      if (!p$series %in% live_series) {
        record(
          "post",
          slug,
          sprintf(
            "Unknown series link: post '%s' references unknown or non-live series '%s'",
            slug,
            p$series
          )
        )
      }
      if (is.null(p$order) || !is.numeric(p$order)) {
        record(
          "post",
          slug,
          sprintf("Post '%s' has missing or non-numeric order", slug)
        )
      }
    }

    if (length(p$related) > 3L) {
      record(
        "post",
        slug,
        sprintf(
          "Post '%s' has %d related links (maximum is 3)",
          slug,
          length(p$related)
        )
      )
    }

    for (r in p$related) {
      target_post <- r$post %||% "<empty>"
      if (!target_post %in% post_slugs) {
        record(
          "post",
          slug,
          sprintf(
            "Broken slug: post '%s' references nonexistent post '%s'",
            slug,
            target_post
          )
        )
      }
      if (identical(target_post, slug)) {
        record("post", slug, sprintf("Post '%s' has a self-link", slug))
      }
      r_type <- r$type %||% "<missing>"
      if (!r_type %in% allowed_types) {
        record(
          "post",
          slug,
          sprintf("Invalid link type '%s' in post '%s'", r_type, slug)
        )
      }
    }
  }

  # Series order: 1..n without gaps or duplicates
  in_series <- Filter(
    function(p) !is.null(p$series) && !is.null(p$order),
    posts
  )
  if (length(in_series) > 0) {
    series_groups <- split(
      vapply(in_series, function(p) as.integer(p$order), integer(1)),
      vapply(in_series, function(p) as.character(p$series), character(1))
    )
    for (sid in names(series_groups)) {
      ords <- series_groups[[sid]]
      if (anyDuplicated(ords) > 0) {
        record(
          "post",
          sid,
          sprintf(
            "Duplicate order in series '%s': parts %s",
            sid,
            paste(ords[duplicated(ords)], collapse = ", ")
          )
        )
      }
      sorted_ords <- sort(unname(ords))
      if (!identical(sorted_ords, seq_along(ords))) {
        record(
          "post",
          sid,
          sprintf(
            "Order gap in series '%s': expected 1..%d, got %s",
            sid,
            length(ords),
            paste(sorted_ords, collapse = ", ")
          )
        )
      }
    }
  }

  if (length(problems) == 0) {
    return(data.frame(
      scope = character(),
      item = character(),
      problem = character(),
      stringsAsFactors = FALSE
    ))
  }

  do.call(rbind, lapply(problems, as.data.frame, stringsAsFactors = FALSE))
}

# Run demo when executed directly
if (sys.nframe() == 0L) {
  demo_dir <- file.path(tempdir(), "check-registry-demo")
  dir.create(
    file.path(demo_dir, "_data"),
    recursive = TRUE,
    showWarnings = FALSE
  )
  dir.create(
    file.path(demo_dir, "posts"),
    recursive = TRUE,
    showWarnings = FALSE
  )
  on.exit(unlink(demo_dir, recursive = TRUE), add = TRUE)

  # Sample registry
  cat(
    "series:\n",
    "  - id: basics\n",
    "    status: live\n",
    "    track: engineering\n",
    "    related:\n",
    "      - {to: testing, type: read-next}\n",
    "  - id: testing\n",
    "    status: planned\n",
    "    track: engineering\n",
    "    title: 'Testing in R'\n",
    "    summary: 'Unit and snapshot testing'\n",
    file = file.path(demo_dir, "_data", "series.yml"),
    sep = ""
  )

  # Sample posts
  make_post <- function(slug, yaml_content) {
    pdir <- file.path(demo_dir, "posts", slug)
    dir.create(pdir, recursive = TRUE, showWarnings = FALSE)
    cat(
      "---\n",
      yaml_content,
      "---\n\nPost body content.\n",
      file = file.path(pdir, "index.qmd"),
      sep = ""
    )
  }

  make_post(
    "intro",
    paste0(
      "title: 'Introduction'\n",
      "series: basics\n",
      "order: 1\n",
      "related:\n",
      "  - {post: advanced, type: read-next}\n"
    )
  )

  # Planted bug: broken slug reference to 'nonexistent-post'
  make_post(
    "advanced",
    paste0(
      "title: 'Advanced Concepts'\n",
      "series: basics\n",
      "order: 2\n",
      "related:\n",
      "  - {post: nonexistent-post, type: builds-on}\n"
    )
  )

  make_post(
    "orphan-summary",
    paste0(
      "title: 'Orphan Summary'\n",
      "related:\n",
      "  - {post: intro, type: see-also}\n"
    )
  )

  registry <- read_registry(file.path(demo_dir, "_data", "series.yml"))
  posts <- scan_posts(file.path(demo_dir, "posts"))
  issues <- check_registry(registry, posts)

  cat("Validated", length(registry), "series and", length(posts), "posts.\n")
  if (nrow(issues) == 0) {
    cat("✓ No registry issues detected.\n")
  } else {
    cat(sprintf("Found %d issue(s):\n", nrow(issues)))
    for (i in seq_len(nrow(issues))) {
      cat(sprintf(
        "  [%s] %s: %s\n",
        issues$scope[i],
        issues$item[i],
        issues$problem[i]
      ))
    }
  }
}

Sources

Quarto & Pandoc documentation

Static site generators & content collections

R package documentation

NoteUpdates
  • 2026-11-13: The site’s test files now carry a site- or post- prefix, so the test named here is tests/testthat/test-site-series-registry.R.