'How to create a custom example environment for r markdown pdf output?
I am hoping to create a custom-styled example environment within r markdown that renders pdf output.
I want something that looks like this or like this, but I still want the example to be numbered, and I want to use the simple syntax
'''{example} <!-- I use ' instead of ` to make it appear in this question -->
Hello
'''
throughout my document. Is this achievable? Thank you in advance!
EDIT: I am adding a minimal example
---
header-includes:
- \newtheorem{theorem}{Theorem}
- \newtheorem{example}{Example}
urlcolor: blue
extension: latex_macros
numbersections: true
output:
bookdown::pdf_document2:
toc: false
biblio-style: apalike
---
'''{example} <!-- I use ' instead of ` to make it appear in this question -->
Hello
'''
Then I get something like this
But I would want the example to be styled and numbered. Maybe put inside a block that look maybe like this (Image from here, but no example number and I can't just use the r markdown block)
Solution 1:[1]
You could use tcolorbox for the example:
---
header-includes: |
\BeforeBeginEnvironment{document}{
\usepackage[most]{tcolorbox}
\let\example\undefined
\let\endexample\undefined
\newtcolorbox[auto counter]{example}{
colback=white,
colbacktitle=black,
arc=0mm,
title={Example~\thetcbcounter:},
bottom=-.7\baselineskip,
colframe=black,
fonttitle=\bfseries
}}
urlcolor: blue
extension: latex_macros
numbersections: true
output:
bookdown::pdf_document2:
toc: false
keep_tex: true
biblio-style: apalike
---
test
```{example}
Hello
```
Solution 2:[2]
You can use some packages as for ordinary LaTeX. I give you an example with the packages thmtools and mdframed.
---
output:
pdf_document:
includes:
in_header: preamble.tex
keep_tex: yes
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
\begin{example}
Hello I am an example.
\end{example}
File preamble.tex:
\usepackage{amsthm,thmtools}
\usepackage{mdframed}
\definecolor{verylightgray}{gray}{0.9}
\declaretheoremstyle[
headfont=\color{black}\normalfont\bfseries,
bodyfont=\color{black}\normalfont\sffamily,
mdframed={
backgroundcolor=verylightgray,
hidealllines=true,
innertopmargin=2pt,
innerbottommargin=2pt,
skipabove=\topsep,
skipbelow=\topsep
}]{mystyle}
\declaretheorem[
style=mystyle,
name=Example
]{example}
A linebreak or a top margin is needed...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Stéphane Laurent |




