Skip to content

Instantly share code, notes, and snippets.

@jcblum
Last active June 13, 2019 18:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcblum/9edafdef1c8d249826b71bbf4c1486c8 to your computer and use it in GitHub Desktop.
Save jcblum/9edafdef1c8d249826b71bbf4c1486c8 to your computer and use it in GitHub Desktop.
Ideas for using `fs` and `rstudioapi` to make relative paths less painful in `blogdown`

Some tools to help with relative paths, and a hasty napkin-sketch of things you might do with them

First, the tools

fs has fantastic tools for path computations!

# install.packages("fs")

# The stuff I'll use below... but there's tons that the package can do
?fs::path
?fs::path_rel
?fs::path_ext_remove

If you’re editing a file, you can find out where it is with the RStudio API

# Assuming I've got one of the `hugo-academic` example blog posts open in my Source pane...
rstudioapi::getSourceEditorContext()$path
#> [1] "~/Documents/website/content/post/2015-07-23-r-rmarkdown.Rmd"

(Note that if you haven’t saved the file yet, the path will be an empty string!)

The simplest use case for path_rel()

Trying to figure out how to go between two places within the public folder? Let path_rel() do the math!

Here's an example with two paths that should exist in any freshly created hugo-academic site:

  • FROM: the example internal project page
  • TO: an image in the img folder
library(fs)

path_rel(
  "public/img/hero-academic.png", 
  start = "public/project/internal-project/index.html"
)
#> ../../../img/hero-academic.png

:-DDD

Napkin-sketch: this could be so much more useful!

I believe all the tools exist to write a little helper that understands (for a given Hugo theme, at least) how things in content and static map onto public, and knows what you're currently working on in RStudio, and can help you link to stuff with less pain.

My extremely hasty and very tiny motivating example:

library(fs)
library(magrittr)

# Let's set up some variables that will help us compute paths based on
# the world that will exist when our site is published
site_root <- path_abs("public")
site_img <- path(site_root, "img")

Now imagine that I’m working again with that hugo-academic example blog post…

# I'll calculate where my post will actually wind up once published
post_live <- rstudioapi::getSourceEditorContext()$path %>% 
  path_rel(start = path_wd("content")) %>% 
  path_ext_remove() %>% 
  path("index.html")

# You know what this post is missing? A big ol' hugo-academic logo!
path(site_img, "hero-academic.png") %>% 
  path_rel(start = path(site_root, post_live))
#> ../../../img/hero-academic.png
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment