简体   繁体   中英

How to list all R Markdown templates in a package?

General Problem

Given a package that provides R Markdown templates, how does one get a list of all valid templates that could be given to the rmarkdown::draft function? That is, for

rmarkdown::draft("my_rmd.Rmd", template_name, some_pkg)

where we know some_pkg , how can one programmatically obtain the valid values for template_name ?

Example Package: reprex

As a concrete example of a template provider, let's use the reprex package. From the RStudio GUI, I know reprex provides two templates. How can one get the list of template_names for the reprex package?

What I've Looked Through

Skimming through the rmarkdown:: methods, I don't see any such functionality. Searching around, I've only found examples for how to write and use templates, but all eventually resort to showing how to load the template via the RStudio GUI dialog. The documentation of the rmarkdown::draft only describes where the templates are stored, but doesn't provide a programmatic example for listing them.

Directory Listing

One solution is to search the package's installation directory for templates. For the reprex case, we have

## get package root directory
pkg_dir <- system.file(package="reprex")

## list all directory names corresponding to templates
list.dirs(paste0(pkg_dir, "/rmarkdown/templates"), recursive=FALSE, full.names=FALSE)
## [1] "reprex-featureful" "reprex-minimal" 

## verify they work
rmarkdown::draft("test", "reprex-minimal", "reprex")

While this works, I find it rather unsatisfactory and would expect there to be a dedicated function for this. But perhaps I overestimate the demand for programmatically working with templates.

available_templates()

Starting with rmarkdown v2.12, there is now an exported function for this. For example,

rmarkdown::available_templates("reprex")

See v2.12 Release Notes .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM