首页 > 解决方案 > blogdown 中的 Gitbook 风格词汇表

问题描述

我正在尝试使用 Hugo 将遗留 gitbook 的词汇表功能添加到 blogdown 中。在 gitbook 中,此功能自动<a>为单独的glossary.md 文件中列出的术语生成标签。词汇表文件的结构如下:

## Term 1
Definition 1

## Term 2
Definition 2

可以在这里看到一个工作示例(在旧版 gitbook 中) 。

我在 Hugo 中找不到这样做的方法,但我认为我应该能够使用 blogdown。我可以使用build.R脚本调用单独的函数来对 .rmd 文件进行查找和替换,将字符串的每个实例替换Term X<span title="Definition X">Term X</span>?

设想的工作流程将类似于:

  1. 复制内容目录,使原始内容目录保持不变
  2. 查找和替换术语(从词汇表文档中的术语到内容目录中的文本)
  3. 调用 blogdown 构建 HTML
  4. Blogdown 调用 Hugo 来渲染站点

这是一个合理的方法/有没有更好的方法?

标签: blogdown

解决方案


我已经解决了。我的阅读表明使用lapply或其他apply家庭在 R 中的计算效率更高,但我for较早地用循环破解了坚果。

build.R脚本中:

#Ensure working directory is the site root

library(R.utils)
library(xfun)

#Move everything to a safe space
copyDirectory(from="content", to="working", recursive=TRUE)

#Draws the glossary from a separate .md file, and separates it out into terms and definitions
glossary <- lapply(strsplit(readLines(con = "content/glossary.md", warn = FALSE), "## |##"), function(x){x[!x ==""]})
glossary <- glossary[lapply(glossary, length)>0] #Tidy up
terms <- glossary[seq_along(glossary) %% 2 > 0] #Separates the terms
defs <- glossary[seq_along(glossary) %% 2 == 0] #And the defs. terms[1] corresponds to defs[1].

#Get files for site
files <- list.files(path="working", pattern = "*.md|*.rmd|*.rmarkdown", recursive = TRUE)

#Replacing bit
setwd("working")
for (file in seq_along(files)) {
  for (term in seq_along(terms)) {
    gsub_file(files[file], sprintf("%s", terms[term]), sprintf("<span title=\"%s\" class=\"glossary\">%s</span>", defs[term], terms[term]), fixed = TRUE)
  }
}
setwd("..")

#Build the site from the new glossaried markdown
blogdown::build_dir('working')

推荐阅读