Julien
Julien

Reputation: 149

Passing parameters from R Markdown to Latex

Good evening, I would like to pass custom parameters from Rmd to the header (using fancyhdr) of a pdf document. I tried the code below, but I don't know how it could interpret \parames$figureno ... and I get that error when knitting:

 ! Undefined control sequence.
\f@nch@och ->\parames 
                      $figureno\strut 
l.169 \end{document}

Here is the code in Rmd:

output: 
pdf_document:
  keep_tex: true
  includes:
      in_header: header.tex
params:
  figureno: "Fig. 1-1"

And the header.tex:

\usepackage{fancyhdr}
\pagestyle{fancy}
\fancyhead[CO,CE]{\parames$figureno}
\fancyfoot[CO,CE]{And this is a fancy footer}
\fancyfoot[LE,RO]{\thepage}
\renewcommand\headrule{%
       \vspace{3pt}
       \hrulefill}

How can I make it working ?

Thank you in advance.

Upvotes: 4

Views: 1754

Answers (2)

Julien
Julien

Reputation: 149

I used the solution proposed by Martin Schmelzer (above). With the advantage that I can still include another *.tex to design the header with static content.

---
template: default-1.17.0.2.tex
title: "Some test..."
figureno: "Fig. 1-1"
output: 
  pdf_document:
    includes:
      in_header: header.tex
    keep_tex: true

---

I inserted these two lines in the main template (default-1.17.0.2.tex):

\usepackage{fancyhdr}
\fancyhead[RO,RE]{$figureno$}

Upvotes: 1

user2554330
user2554330

Reputation: 44788

You can sort of do this, but it's tricky. A way that works is to put all of header.tex into the header-includes: field of the YAML header. (Unfortunately, you can't have both header-includes: and includes: in_header.) You can execute R code within strings in the YAML header, so that's how you'd get your \fancyhead set properly. For example:

---
output: 
  pdf_document:
    keep_tex: true
header-includes: 
  - \usepackage{fancyhdr}
  - \pagestyle{fancy}
  - '`r paste0("\\fancyhead[CO,CE]{", params$figureno, "}")`'
  - \fancyfoot[CO,CE]{And this is a fancy footer}
  - \fancyfoot[LE,RO]{\thepage}
  - \renewcommand\headrule{\vspace{3pt}\hrulefill}
params:
  figureno: "Fig. 1-1"
---

Note that backslashes need to be doubled in the R code paste0("\\fancyhead[CO,CE]{", params$figureno, "}") to end up with a single backslash in the result.

Also note that the R code needs to be inline R code wrapped in backticks and then also wrapped in quotes as a string constant. I've seen recommendations that single quotes be used on the string constant instead of double quotes, but I don't know if that really matters.

Upvotes: 4

Related Questions