Reputation: 77096
Consider the following Rmd file,
---
title: "Untitled"
author: "baptiste"
date: "`r Sys.Date()`"
output: html_document
test: "`r paste('_metadata.yaml')`"
---
```{r}
cat(rmarkdown::metadata$test)
```
The date is processed (knitted) by R before being passed to pandoc for conversion to md and html. The custom field test
, however, is unevaluated.
What's the difference? Can one force knitr/rmarkdown to evaluate an arbitrary field in the yaml header?
Note: the actual purpose is not to just print()
a filename as in this dummy example, but to load an external yaml file containing metadata (author information), process it with R, and output a string that will be injected in the document.
Upvotes: 11
Views: 4273
Reputation: 15897
The standard metadata field data
and your custom field test
are not actually treated any differently. This code:
---
title: "Untitled"
author: "baptiste"
date: "`r Sys.Date()`"
output:
html_document:
keep_md: yes
test: "`r paste('_metadata.yaml')`"
---
```{r}
cat(rmarkdown::metadata$date)
cat(rmarkdown::metadata$test)
```
leads to the following output:
As you can see, also date
was not evaluated. I have not found any functionality in the rmarkdown
or knitr
packages. But the following simple function does the trick at least for your simple example:
---
title: "Untitled"
author: "baptiste"
date: "`r Sys.Date()`"
output:
html_document:
keep_md: yes
test: "`r paste('_metadata.yaml')`"
---
```{r}
eval_meta <- function(x) eval(parse(text = gsub("`|r", "", x)))
eval_meta(rmarkdown::metadata$date)
eval_meta(rmarkdown::metadata$test)
```
Whether that works in your more complex situation is another question, however.
Upvotes: 4
Reputation: 44788
It does evaluate the code. If you run foo.Rmd with
rmarkdown::render("foo.Rmd", clean = FALSE)
you'll see an intermediate file (the pandoc input) called foo.knit.md
left behind. It will look like this:
---
title: "Untitled"
author: "baptiste"
date: "2017-08-12"
output: html_document
test: "_metadata.yaml"
---
```r
cat(rmarkdown::metadata$test)
```
```
## `r paste('_metadata.yaml')`
```
I don't know how to see that from within the document (your example shows that metadata$test
doesn't work), but there's probably some trick or other to get at it.
Upvotes: 4