I am trying to use a parameterized path for a reference_docx
in a Rmarkdown document with rmarkdown::word_document
output format, in a similar way as e.g. is done here for the bibliography file (section Bibliograghy and Citation YAML options).
However, it seems like this feature does not work for the reference_docx
option, as expressions passed to the arguments of the output format function (rmarkdown::word_document
, or bookdown::word_document2
for that matter) are interpreted literally instead of evaluated. See e.g. this minimal reprex:
---
params:
ref: www/Template_doc.docx
output:
word_document:
reference_docx: www/Template_doc.docx
---
Some markdown stuff
---
params:
ref: www/Template_doc.docx
output:
word_document:
reference_docx: "`r params$ref`"
---
Some markdown stuff
This example gives the following error when trying to knit:
pandoc.exe: `r params$ref`: openBinaryFile: does not exist (No such file or directory)
That is, it tries to use `r params$ref`
exactly as the file name, instead of evaluating params$ref
I have also tried with (as explained in this answer):
!r params$ref
: it apparently ignores the !r
altogether and considers params$ref
to be the intended file name
!expr params$ref
: it gives the following error:
Error: object 'params' not found
Error in yaml::yaml.load(..., eval.expr = TRUE) :
Could not evaluate expression: params$ref
Calls: <Anonymous> ... parse_yaml_front_matter -> yaml_load -> <Anonymous>
Execution halted
Any ideas on how to solve this? Many thanks!!
Apparently, the problem is with trying to access params
from within the yaml
header itself. As stated here,
Finally,
params
(the list of parameters provided within the knitting environment) is not available for yaml expressions.
Other than that, the field reference_docx
can evaluate expressions the same way as other yaml
header fields, see e.g..
Consequently, my own (working) example, adapted to this, would be:
---
params:
ref: www/Template_doc.docx
output:
word_document:
reference_docx: !expr file.path("www", "Template_doc.docx")
---
Some markdown stuff