Cannot render custom blocks with cat()

Viewed 54

As explained in this chapter of the R Markdown Cookbook, it is possible to make custom blocks in R Markdown files with this syntax (here, to center some text):

:::{.center data-latex=""}
Hello
:::

However, using cat() to render this sort of block (as explained in this chapter) does not work.

Full example:

---
output: rmarkdown::pdf_document
---

<!-- WORKS -->
:::{.center data-latex=""}
Hello
:::

<!-- DOES NOT WORK -->
```{r, results='asis', echo=FALSE}
print(
  '
  :::{.center data-latex=""}\n
  Hello\n
  :::
'
)
```

Why is the second part not rendering correctly? How to solve that?

1 Answers

There are two issues:

  1. You use print() instead of cat() (even if you refer to cat() in your post
  2. You put spaces at the beginning of each line which prevents the custom block to be rendered.
  3. If you prefer the lines to be indented (as I do) then I would suggest make each line a separate string as I do in the second example. This also has the advantage that you could add the line breaks via the sep argument instead of having to add them manually.

Reproducible example:

---
output: 
  rmarkdown::pdf_document:
    keep_md: true
---

<!-- WORKS -->
:::{.center data-latex=""}
Hello
:::

<!-- WORKS TOO -->
```{r, results='asis', echo=FALSE}
cat('
:::{.center data-latex=""}\n
Hello\n
:::
', sep = "\n"
)
```

<!-- WORKS TOO -->
```{r, results='asis', echo=FALSE}
cat(':::{.center data-latex=""}',
    'Hello',
    ':::', sep = "\n"
)
```

enter image description here

Related