4.4 Quarto
Quarto Guide: https://quarto.org/docs/guide/
Quarto Tutorial: https://jmjung.quarto.pub/m02-advanced-literate-programming/#learning-outcomes
Run Quarto in VS Code: https://quarto.org/docs/tools/vscode/index.html
Run Cell
Quarto Command | Keyboard Shortcut |
---|---|
Run Current Cell | ⇧ + Enter |
Run Selected Line(s) | ⌘ + Enter |
Host Quarto on GitHub Pages.
To get started, change your project configuration _quarto.yml
to use docs
as the output-dir
.
Then, add a .nojekyll
file to the root of your repository that tells GitHub Pages not to do additional processing of your published site using Jekyll (the GitHub default site generation tool):
- Note that
.nojekyll
’s location is different than that ofbookdown
, which is at/docs
folder.
4.4.0.1 Only re-render changed files
You can add the following to your _quarto.yml
file to only re-render changed files:
When freeze: auto
is enabled, Quarto checks for modifications in the source files of your computational documents. If no changes are detected, Quarto will utilize the cached results from previous computations, skipping the re-execution of code chunks.
This significantly speeds up rendering times, especially for large projects with many computational documents. ✅
There are drawbacks: some files may not be updated in time.
- Use
freeze: false
to force re-rendering of all files when you are able to submit your changes. - Use
freeze: auto
when you are editing actively and want to see your changes in time.
Strengths of Quarto:
- hoverable citations and cross-references, easy to read
- easy subplots
Weakness of Quarto:
slow compared to
Bookdown
Workaround:
- Use
quarto preview
in terminal to enable live preview - Set
freeze: auto
in_quarto.yml
to only re-render changed files.
- Use
Issues when you want to compile one single page within a package. Changes are not reflected in time unless you render the whole website.
Workaround: Need to exclude from project index, and need file header
yaml
to import mathjax settings and themes.Bookdown
is reliable. Don’t needyaml
in singleRmd
, website theme will apply automatically.Not support
rstudioapi
functions. E.g., the following is often used to set working directory to the folder where the current script is located.But it does NOT work in Quarto.
4.4.1 Book Structure
book:
chapters:
- index.qmd
- preface.qmd
- part: dice.qmd
chapters:
- basics.qmd
- packages.qmd
- part: cards.qmd
chapters:
- objects.qmd
- notation.qmd
- modifying.qmd
- environments.qmd
- references.qmd
appendices:
- tools.qmd
- resources.qmd
The
index.qmd
file is required (because Quarto books also produce a website in HTML format). This page should include the preface, acknowledgements, etc.The remainder of
chapters
includes one or more book chapters.You can divide your book into parts using
part
within the bookchapters
.Note that the markdown files
dice.qmd
andcards.qmd
contain the part title (as a level one heading) as well as some introductory content for the part.If you just need a part title then you can alternatively use this syntax:
The
references.qmd
file will include the generated bibliography (see References below for details).
Syntax differences with R Markdown:
Code chunks
Both R markdown and Quarto can use the following ways to specify chunk options:
Use
tag=value
in the chunk header```{r}
.Alternatively, you can write chunk options in the body of a code chunk after
#|
, e.g.,tag: value
is the YAML syntax. Logical values in YAML can be any of:true/false
,yes/no
, andon/off
. They all equivalent toTRUE/FALSE
(uppercase) in R.Options format:
- space after
#|
and colon:
- TRUE/FALSE need to be in uppercase
Note that Quarto accepts Rmd’s way of specifying chunk options. The difference is that Quarto’s label for figures must start with
fig-
, while Rmd accepts any labels.- space after
4.4.2 PDF Options
Use the pdf
format to create PDF output. For example:
---
title: "Lab 1: Solutions"
format:
pdf:
include-in-header: ../latex/preamble.tex
fontsize: 12pt
pdf-engine: xelatex
---
See HERE for all available options.
See Metadata variables for yaml options that Pandoc recognizes.
Title & Author
PDF Options | Functions |
---|---|
title |
Document title |
date |
Document date |
author |
Author or authors of the document |
abstract |
Summary of document |
Format Options
PDF Options | Functions |
---|---|
pdf-engine |
Specify the PDF engine to use. Options include pdflatex , xelatex , and lualatex . The default is xelatex . |
PDF Options | Functions |
---|---|
include-in-header |
Include contents at the end of the header. Specify your pdf template here. |
Subkeys for include-in-header
file
: path to a file to include at the end of the header.text: |
: include raw latex content in the YAML header.|
indicates that the content is in multiple lines.If you omit
file:
ortext:
, Quarto assumesfile:
by default.
Use example
format:
pdf:
include-in-header:
- text: |
\usepackage{eplain}
\usepackage{easy-todo}
- file: packages.tex
- macros.tex # assume file by default
- Note that you need the dash
-
beforetext:
andfile:
to indicate a list of items.
Any packages specified using includes that you don’t already have installed locally will be installed by Quarto during the rendering of the document.
header-includes: |
is a pandoc variable for including raw LaTeX code in the document header.
- use example in quarto doc
- pandoc doc for
header-includes
header-includes: |
\RedeclareSectionCommand[
beforeskip=-10pt plus -2pt minus -1pt,
afterskip=1sp plus -1sp minus 1sp,
font=\normalfont\itshape]{paragraph}
\RedeclareSectionCommand[
beforeskip=-10pt plus -2pt minus -1pt,
afterskip=1sp plus -1sp minus 1sp,
font=\normalfont\scshape,
indent=0pt]{subparagraph}
Format & Typesettings
PDF Options | Functions |
---|---|
toc-depth |
Specify the number of section levels to include in the table of contents. The default is 3 |
number-sections |
Number section headings rendered output. By default, sections are not numbered. |
number-depth |
By default, all headings in your document create a numbered section. |
PDF Options | Functions |
---|---|
df-print |
Method used to print tables in Knitr engine documents. - default : Use the default S3 method for the data frame. - kable : Default method. Markdown table using the knitr::kable() function. - tibble : Plain text table using the tibble package. - paged : HTML table with paging for row and column overflow. |
Q: How to print dollar sign in pdf output?
A: qmd
supports $
directly. No need to escape.
After rendering, the following info will appear in the console:
pandoc
to: latex
output-file: lab1_solutions.tex
standalone: true
pdf-engine: xelatex
variables:
graphics: true
tables: true
default-image-extension: pdf
metadata
documentclass: scrartcl
classoption:
- DIV=11
- numbers=noendperiod
papersize: letter
header-includes:
- \KOMAoption{captions}{tableheading}
block-headings: true
title: 'Lab 1: Solutions'
fontsize: 12pt
Note that documentclass: scrartcl
is the KOMA-Script article class.
It has good looking default settings, and is highly customizable.
4.4.2.1 Title Margin
One issue is it might have too wide margins around the title.
To reduce the margin above the title, add the following line to your preamble.tex
file:
% reduce title top margin
\usepackage{xpatch}
\makeatletter
\xpatchcmd{\@maketitle}{\vskip2em}{
% Insert here the space you want between the top margin and the title.
\vspace{-2em} % Example of smaller margin.
}{}{}
\makeatother
To reduce the margin below the title, in individual qmd
file, add the following line after the YAML header:
fenced divs
code chunks
For pdf output, it is possible to write LaTeX code directly in Markdown document using fenced divs or code chunks with {=latex}
.
- Don’t forget the equal sign before
latex
.
ref: R Markdown Cookbook: Section 6.11 Write raw LaTeX code
4.4.2.2 Templates
See HERE for an overview of how to set template for tex
files.
- pakage setup
- article typsetting
Starter template for qmd
file.
- yaml header
- structure of your
qmd
4.4.3 HTML Theming
One simple theme
Enable dark and light modes
format:
html:
include-in-header: themes/mathjax.html
respect-user-color-scheme: true
theme:
dark: [cosmo, themes/cosmo-dark.scss]
light: [cosmo, themes/cosmo-light.scss]
- See HTML basic yaml for basic option settings.
- See HTML format reference for a complete list of all available options.
respect-user-color-scheme: true
honors the user’s operating system or browser preference for light or dark mode.
Otherwise, the order of light and dark elements in the theme or brand will determine the default appearance for your html output. For example, since the dark
option appears first in the first example, a reader will see the light appearance by default, if respect-user-color-scheme
is not enabled.
As of Quarto 1.7, respect-user-color-scheme
requires JavaScript support: users with JavaScript disabled will see the author-preferred (first) brand or theme.
Custom Themes
Your custom.scss
file might look something like this:
/*-- scss:defaults --*/
$h2-font-size: 1.6rem !default;
$headings-font-weight: 500 !default;
/*-- scss:rules --*/
h1, h2, h3, h4, h5, h6 {
text-shadow: -1px -1px 0 rgba(0, 0, 0, .3);
}
Note that the variables section is denoted by
/*-- scss:defaults --*/
: the defaults section (where Sass variables go)Used to define global variables that can be used throughout the theme.
/*-- scss:rules --*/
: the rules section (where normal CSS rules go)Used to define more fine grained behavior of the theme, such as specific styles for headings, paragraphs, and other elements.
Theme Options
You can do extensive customization of themes using Sass variables. Bootstrap defines over 1,400 Sass variables that control fonts, colors, padding, borders, and much more.
The Sass Variables can be specified within SCSS files. These variables should always be prefixed with a $
and are specified within theme files rather than within YAML options
Category | Variable | Description |
---|---|---|
Colors | $body-bg |
The page background color. |
$body-color |
The page text color. | |
$link-color |
The link color. | |
$input-bg |
The background color for HTML inputs. | |
$popover-bg |
The background color for popovers (for example, when a citation preview is shown). |
You can see all of the variables here:
https://github.com/twbs/bootstrap/blob/main/scss/_variables.scss
Note that when you make changes to your local .scss
, the changes will be implemented in-time. That is, you don’t need to re-build your website to see the effects.
Ref:
Quarto document: https://quarto.org/docs/output-formats/html-themes.html
Check sass variables: https://bootswatch.com
4.4.4 Render Quarto
Rendering the whole website is slow. When you are editing a new section/page, you may want to edit as a standalone webpage and when you are finished, you add the qmd
file to the _quarto.yml
file index.
Difference btw a standalone webpage from a component of a qmd
project
Standalone webpage: include
yaml
at the header of the file.Fast compile and rendering. ✅
A component of
qmd
project: added to the file index, noyaml
needed, format will automatically apply.Slow, need to render the whole
qmd
project in order to see your change.
In terminal
This will provide live preview of the document in your web browser. Newest changes will be reflected while you edit the document. ✅
Render a Quarto document to HTML using the command line:
Quarto Preview: display output in the external web browser.
$ quarto preview 0304-Quarto.Rmd # all formats $ quarto preview 0304-Quarto.Rmd --to html # specific format
Note that
quarto render
can be used to Rmd files too.You can also render a Quarto project using:
In VS Code
By default Quarto does not automatically render .qmd
or .ipynb
files when you save them. This is because rendering might be very time consuming (e.g. it could include long running computations) and it’s good to have the option to save periodically without doing a full render.
You have to refresh to see your updates when using VS Code command palette quarto preview.
You can render a Quarto document in VS Code using the command palette:
Quarto: Render Document
to render the document.Quarto: Render Project
to render the entire project.Quarto: Preview
to preview the default document in a web browser. If you want to preview a different format, use theQuarto: Preview Format
command:
This will show a preview of the project in the internal browser.
However, you can configure the Quarto extension to automatically render whenever you save. In settings, set quarto.renderOnSave
to true
.
You might also want to control this behavior on a per-document or per-project basis. If you include the editor: render-on-save
option in your document or project YAML it will supersede whatever your VS Code setting is. For example:
Q: Quarto Preview pane not refreshing and updating changes.
A: The issue seems to come from the --no-watch-inputs
option to the preview command, preventing the live update. ↩︎
Use the following command in terminal to enable live preview:
Copy and paste the url to the internal browser in VS Code. The command supports live preview. When you make changes to your qmd
file and save, the preview will be updated in time.
In R
quarto::quarto_render(input = NULL, output_format = "html")
can be used to render a Quarto document or project in R.
If
input
is not specified, it will render the current Quarto project. Ifinput
is specified, it will render the specified Quarto document.If
output_format
is not specified, it will render the document to HTML. You can specify other formats such as PDF or Word.output_format = "all"
will render all formats specified in the_quarto.yml
file.
# Render a Quarto document to HTML
quarto::quarto_render("0304-Quarto.Rmd", output_format = "html")
# Render a Quarto project to HTML
quarto::quarto_render(output_format = "html")
# Render a Quarto document to PDF
quarto::quarto_render("0304-Quarto.Rmd", output_format = "pdf")
# Render a Quarto project to PDF
quarto::quarto_render(output_format = "pdf")
Alternatively, you can use the Render button in RStudio. The Render button will render the first format listed in the document YAML. If no format is specified, then it will render to HTML.
4.4.5 Cross References
Add labels
Two options:
- Code cell: add option
label: prefix-LABEL
- Markdown: add attribute
#prefix-LABEL
- Note that the prefix should be connected to the label with a hyphen
-
. - Note that the hash sign
#
is required.
- Note that the prefix should be connected to the label with a hyphen
- Code cell: add option
Add references:
@prefix-LABEL
, e.g.You can see in @fig-scatterplot, that...
Element | ID | How to cite |
---|---|---|
Figure | #fig-xxx |
@fig-xxx |
Table | #tbl-xxx |
@tbl-xxx |
Equation | #eq-xxx |
@eq-xxx |
Section | #sec-xxx |
@sec-xxx |
Cross-reference to a figure:

Figure 4.1: Scatter plots example
See Figure 4.1 (@fig-scatter
) for the scatter plots.
You can customize the prefix of the reference (Figure x) using crossref/*-prefix
options in YAML.
Cross-references to Equations
@eq-cross_sectional_hetero
givesEquation 1
. There are no parentheses around the number.With the
Equation
prefx, but no parentheses around labels.([-@eq-cross_sectional_hetero])
gives only the tag(1)
, note that you need to add the parentheses yourself.An alternative way is to use
\eqref{eq-cross_sectional_hetero}
fromamsmath
package, which gives(1)
with parentheses automatically. You need to add the prefix Eq. yourself. ↩︎
You can customize the appearance of inline references by either changing the syntax of the inline reference or by setting options.
Here are the various ways to compose a cross-reference and their resulting output:
Type | Syntax | Output |
---|---|---|
Default | @fig-elephant |
Figure 1 |
Capitalized | @Fig-elephant |
Figure 1 |
Custom Prefix | [Fig @fig-elephant] |
Fig 1 |
No Prefix | [-@fig-elephant] |
1 |
Note that the capitalized syntax makes no difference for the default output, but would indeed capitalize the first letter if the default prefix had been changed via an option to use lower case (e.g. “fig.”).
Change the prefix in inline reference using *-prefix
options. You can also specify whether references should be hyper-linked using the ref-hyperlink
option.
---
title: "My Document"
crossref:
fig-prefix: figure # (default is "Figure")
tbl-prefix: table # (default is "Table")
ref-hyperlink: false # (default is true)
---
4.4.6 Equations
4.4.6.1 Individual qmd
file
Load MathJax Config
For individual qmd
files, load mathjax.html
in YAML
---
title: "Model specifications"
author: "GDP and climate"
date: "2025-05-13"
format:
html:
toc: true
self-contained: true
html-math-method: mathjax
include-in-header: mathjax.html
from: markdown+tex_math_single_backslash
---
from
can be a top-level option (same level astitle
) or a third-level option underformat/html
in YAML.- It specifies formats to read from.
- Extensions can be individually enabled or disabled by appending
+EXTENSION
or-EXTENSION
to the format name (e.g. markdown+emoji). - See Quarto Extensions for available extensions.
from: markdown+tex_math_single_backslash
tells Quarto/Pandoc to read the input as Pandoc Markdown with thetex_math_single_backslash
extension enabled.from
tex_math_single_backslash
supports\(
and\[
as math delimiters.- See Pandoc: Math Input for available math extensions.
In mathjax.html
, define the MathJax configuration, e.g., user-defined macros.
<script>
MathJax = {
tex: {
tags: 'ams', // should be 'ams', 'none', or 'all'
macros: { // define TeX macro
RR: "{\\bf R}",
bold: ["{\\bf #1}", 1]
},
},
};
</script>
tags: 'ams'
allows equation numbering.
4.4.6.2 Quarto project
In _quarto.yml
,
format:
html:
include-in-header:
- file: themes/mathjax.html # MathJax for LaTeX custom macro support
- file: themes/common-header.html # load js scripts and external css (e.g., font-awesome) for all pages
from: markdown+tex_math_single_backslash
Note that from
is under html
, rather than at the top level of YAML.
Equations need to be labeled to be numbered and cross-referenced.
- Note that labels must begin with
#eq-xxx
. Don’t forget the hyphen-
betweeneq
andxxx
. - Put the label after the
$$
and inside curly braces{}
. - References to equations are made using
@eq-xxx
.
Difference with
bookdown
.bookdown
, on the other hand, use(\#eq:label)
(must use colon) after the equation but inside the$$
.
Math delimiters
Issue: Cannot use \(
and \[
for math delimiters.
Fix: Add from: markdown+tex_math_single_backslash
to YAML frontmatter. Source
---
title: "Quarto Playground"
from: markdown+tex_math_single_backslash
format:
html:
html-math-method: mathjax
---
Inline math example: \( E = mc^2 \)
Block math example:
\[
a^2 + b^2 = c^2
\]
form
: Format to read from. Extensions can be individually enabled or disabled by appending +EXTENSION or -EXTENSION to the format name (e.g. markdown+emoji
).
Extension: tex_math_single_backslash
Causes anything between \(
and \)
to be interpreted as inline TeX math, and anything between \[
and \]
to be interpreted as display TeX math. Note: a drawback of this extension is that it precludes escaping (
and [
.
Refer to Docs of Quarto and Pandoc:
https://quarto.org/docs/reference/formats/html.html#rendering
https://pandoc.org/MANUAL.html#extension-tex_math_single_backslash
https://pandoc.org/MANUAL.html#extension-tex_math_double_backslash
Q: How to get rid of the qmd
dependence file?
A: Use
4.4.7 Extensions
4.4.7.1 Color Text
Create a filter to apply blue text color to fenced div.
- Created a minimal local color-text filter:
- Added
_quiz/_extensions/color-text/color-text.lua
- It supports the
.blue
class for both blocks and inline spans:- HTML: adds
style="color: blue;"
- PDF: wraps with LaTeX xcolor; automatically injects
\usepackage{xcolor}
- HTML: adds
- Added
- Updated the
qmd
file YAML to reference this local filter:- filters:
_extensions/color-text/color-text.lua
- filters:
- You can use fenced divs and inline spans with
.blue
.
Use example
In the yaml header of your
qmd
file, add the following line to reference the local filter:Use the
.blue
class in your markdown content:
4.4.7.2 Emoji
In the yaml, add the emoji
extension to the from
option in document metadata.
For markdown formats that support text representations of emojis 😁 (e.g. :grinning:
), the text version will be written. For other formats the literal emoji character will be written. Currently, the gfm and hugo (with enableEmoji = true
in the site config) formats both support text representation of emojis.
Note: This does NOT work for quarto pdf. Use twemoji approach instead. See below.
How to add more emoji later:
Open
twemoji_manifest.json
and append new code points to the emoji object- Example:
"1f44d": ["👍", ":thumbsup:"]
How to find the code points of an emoji:
- Example:
Run the fetcher again:
Within the project directory:
From anywhere:
$'/Users/menghan/Documents/language/norsk/norskprøver/B2/exam notes/emoji/fetch_twemoji.sh' Exists: 1f4a1.png Exists: 1f4c8.png Exists: 1f4dd.png Exists: 1f539.png Exists: 1f600.png Exists: 1f604.png Exists: 1f680.png Exists: 26a0.png Downloading: 2705.png Done. Files saved in ~/Documents/language/norsk/norskprøver/B2/exam notes/emoji. Map to filter names as needed (already matching).
The script downloads only missing PNGs. If you add more codes to
twemoji_manifest.json
, just run it again.To refresh files, delete specific PNGs (or all) in emoji and rerun.
Add to
unicode_map
inemoji.lua
to point to the same filename.- Example:
["⚠️"] = "26a0.png",
This ensures when you use the emoji directly, it maps to the correct image file.
- Example:
Optionally add a shortcode mapping in
emoji.lua
’semoji_map
to point to the same filename.- Example:
[":warning:"] = "26a0.png",
This allows you to use the shortcode
:warning:
in addition to the direct emoji.- Example:
🎯 Usage Examples
You can now use emojis in your QMD files in two ways:
- Direct Unicode: Great job! 👍 This is amazing! 🎉
- Shortcodes: Great job!
:thumbsup:
This is amazing!:tada:
ref:
4.4.8 Divs and Spans
You can add classes, attributes, and other identifiers to regions of content using Divs and Spans.
- classes:
.class
- identifiers:
#id
- key-value attributes:
key="value"
Note
They are separated by spaces, do NOT use commas.
This is different from
bookdown
, which uses commas.Order: identifiers, classes, and then key-value attributes.
Logical attributes:
true/false
,yes/no
, andon/off
are all equivalent toTRUE/FALSE
in R.It is optional to enclose in quotes.
Div example
Once rendered to HTML, Quarto will translate the markdown into:
A bracketed sequence of inlines, as one would use to begin a link, will be treated as a <span>
with attributes if it is followed immediately by attributes:
Once rendered to HTML, Quarto will translate the markdown into
4.4.9 Theorems
::: {#thm-line}
The equation of any straight line, called a linear equation, can be written as:
$$
y = mx + b
$$
:::
See @thm-line.
In Quarto, #thm-line
is a combined command us .theorem #thm-line
in bookdown. In bookdown, the label can be anything, does not have to begin with #thm-
. But in Quarto, #thm-line
is restrictive, it indicates the thm
environment and followed by the label of the theorem line
.
Theorem 4.1 The equation of any straight line, called a linear equation, can be written as:
\[ y = mx + b \]
See Theorem 4.1.
To add a name to Theorem, use name="..."
.
::: {#thm-topo name="Topology Space"}
A topological space $(X, \Tcal)$ is a set $X$ and a collection $\Tcal \subset \Pcal(X)$ of subsets of $X,$ called open sets, such that ...
:::
See Theorem @thm-topo.
Theorem 4.2 (Topology Space) A topological space \((X, \Tcal)\) is a set \(X\) and a collection \(\Tcal \subset \Pcal(X)\) of subsets of \(X,\) called open sets, such that …
See Theorem 4.2.
Change the label prefix:
cnj-title
: The title prefix used for conjecture captions.cnj-prefix
: The prefix used for an inline reference to a conjecture.
4.4.10 Callouts
There are five different types of callouts available.
- note (blue)
- tip (green)
- important (red)
- warning (amber 比 caution 更亮眼 vivid )
- caution (orange)
The color and icon will be different depending upon the type that you select.
::: {.callout-note}
Note that there are five types of callouts, including:
`note`, `warning`, `important`, `tip`, and `caution`.
:::
::: {.callout-tip}
## Tip with Title
This is an example of a callout with a title.
:::
::: {.callout-caution collapse="true"}
## Expand To Learn About Collapse
This is an example of a 'folded' caution callout that can be expanded by the user. You can use `collapse="true"` to collapse it by default or `collapse="false"` to make a collapsible callout that is expanded by default.
:::
Here are what the various types look like in HTML output:
- Callout heading can be defined using
title = "Heading"
in the callout header, or## Heading
in the callout bodyIt can be any level of heading.
icon = false
to disable the icon in the callout.- To cross-reference a callout, add an ID attribute that starts with the appropriate callout prefix, e.g.,
#nte-xxx
. You can then reference the callout using the usual@nte-xxx
syntax. appearance = "default" | "simple" | "minimal"
default
: to use the default appearance with a background color and border.simple
: to remove the background color, but keep the border and icon.minimal
: A minimal treatment that applies borders to the callout, but doesn’t include a header background color or icon.appearance="minimal"
is equivalent toappearance = "simple" icon = false
in the callout header.
You can style callouts using CSS. For example, the change font size and alignment of text, you can use the following CSS:
::: {.callout-important appearance="minimal"}
## Research Question
<center style="font-size: 1.5em; font-weight: bold;">
Does expenditure per student affect student performance \
in elementary school education?
</center>
:::
4.4.10.1 Nested Callouts
You can nest callouts within other callouts. For example:
::: {.callout-warning}
## Warning with Nested Callout
This is an example of a warning callout that contains a nested note callout.
::: {.callout-note}
This is a nested note callout.
:::
:::
Note that you need to put a blank line before and after the nested callout to ensure proper rendering.
4.4.10.2 Cross-reference Callouts
To cross-reference a callout, add an ID attribute that starts with the appropriate callout prefix (see Table blow). You can then reference the callout using the usual @
syntax. For example, here we add the ID #tip-example
to the callout, and then refer back to it:
::: {#tip-example .callout-tip}
## Cross-Referencing a Tip
Add an ID starting with `#tip-` to reference a tip.
:::
See @tip-example...
Note that the ID attribute must come first, before the class attribute.
This follows the general rule for Divs and Spans that IDs must come before classes.
The prefixes for each type of callout are:
Prefixes for callout cross-references
Callout Type | Prefix |
---|---|
note |
#nte- |
— | — |
tip |
#tip- |
warning |
#wrn- |
important |
#imp- |
caution |
#cau- |
Cross-referencing callouts is currently only supported for HTML, PDF and MS Word.
4.4.11 Conditional Content
In some cases you may want to create content that only displays for a given output format (or only displays when not rendering to a format). You can accomplish this by creating divs, spans and code blocks with the .content-visible
and .content-hidden
classes.
E.g., you have a home assignment file and you want to have two versions of it: one for questions only, and the other for questions and solutions.
You can set a metadata variable in yaml, e.g., solutions: true
or solutions: false
.
---
title: "Quiz: Linear Regression and Hypothesis Testing (p1)"
from: markdown+tex_math_single_backslash
solution: false
# solution: true
format:
pdf:
include-in-header: ../latex/preamble.tex
fontsize: 12pt
---
Then, in the body of your document, you can use the following syntax to conditionally include or exclude content based on the value of the solutions
variable.
::: {.content-visible when-meta="solutions"}
This content will only be visible if `solutions` is set to `true`.
Put your solutions here.
:::
Expected behavior:
- If
solutions: true
, the content will be displayed. - If
solutions: false
, the content will be hidden.
You can use multiple levels of metadata keys separated by periods. For example,
::: {.content-hidden unless-meta="path.to.metadata"}
This content will be hidden unless there exists a metadata entry like such:
```yml
path:
to:
metadata: true
```
:::
You need to use unless-meta="path.to.metadata"
to refer to your
user defined metadata key.
4.4.11.1 Set up multiple profiles
You can also set up multiple profiles in _quarto.yml
, so you can just run quarto render --profile with-solutions
/ --profile no-solutions
in terminal to render the document with or without solutions.
project:
type: book
output-dir: docs
profiles:
with-solutions:
metadata:
solutions: true
no-solutions:
metadata:
solutions: false
You can then render the document with solutions using --profile
argument:
Default profile
To define a default profile, add a default
option to the profile
key. For example, to make the with-solutions
profile the default, you can use the following configuration:
Then, you can simply run quarto render
without specifying a profile, and it will use the with-solutions
profile by default.
4.4.11.2 Conditional Code Blocks
Q: Conditional contents NOT working for code blocks.
A: It’s because .content-visible
runs after code execution. knitr executes the chunk and emits output even if the wrapper later hides the surrounding Markdown. Control the chunk itself with the meta flag.
Solution: Use params in rmarkdown.
In the YAML header, define a parameter
solution
with a default value offalse
.--- title: "Home Assignment" from: markdown+tex_math_single_backslash params: solution: false # solution: true ---
solution: false
means do not show solutions by default.solution: true
means show solutions.
Using a code chunk to get the value of the parameter. Put it at the beginning of the document as part of a global setup.
For following code chunks, you can use
eval=.solution, include=.solution
to control whether to evaluate and include the chunk based on the value of.solution
.- When
.solution
isTRUE
, the chunk will be evaluated and included in the output.- If you still want to evaluate but not include in the output, use
include=.solution
only
- If you still want to evaluate but not include in the output, use
- when
.solution
isFALSE
, the chunk will not be evaluated or included in the output.
- When
For regular text, use fenced divs with
.content-visible
andwhen-meta="solution"
to conditionally include or exclude content based on the value of thesolution
parameter.::: {.content-visible when-meta="params.solution"} This content will only be visible if `solution` is set to `true`. Put your solutions here. :::
- Use the attributes
unless-meta
andwhen-meta
, and use periods.
to separate metadata keys. solution
is a second-level key underparams
, so you need to useparams.solution
to refer to it.
- Use the attributes
Use scenarios:
- When preparing the assignment, you can set
solution: true
to see the solutions while editing. - After you finish editing, set
solution: false
to hide the solutions before submission.
When you want to render the document with solutions, you can set the parameter solution
to true
in the YAML header or use command line arguments.
ref:
- https://jadeyryan.quarto.pub/cascadia-quarto/4-conditionals/
- meta variables: https://quarto.org/docs/authoring/variables.html
References: