11.13 Add attributes to text output blocks (*)
In Section 7.3, we showed some examples of styling source and text output blocks based on the chunk options
class.output. Actually, there is a wider range of similar options in knitr, such as
class.error. These options can be used to add class names to the corresponding text output blocks, e.g.,
class.error adds classes to error messages when the chunk option
error = TRUE (see Section 11.2). The most common application of these options may be styling the output blocks with CSS rules defined according to the class names, as demonstrated by the examples in Section 7.3.
Typically, a text output block is essentially a fenced code block, and its Markdown source looks like this:
When the output format is HTML, it is usually16 converted to:
class.* options control the
class attribute of the
<pre> element, which is the container of the text output blocks that we mentioned above.
In fact, the class is only one of the possible attributes of the
<pre> element in HTML. An HTML element may have many other attributes, such as the width, height, and style, etc. The chunk options
attr.error, allow you to add arbitrary attributes to the text output blocks. For example, with
attr.source = 'style="background: pink;"', you may change the background color of source blocks to pink. The corresponding fenced code block will be:
And the HTML output will be:
As a technical note, the chunk options
class.* are just special cases of
class.source = 'numberLines' is equivalent to
attr.source = '.numberLines' (note the leading dot here), but
attr.source can take arbitrary attribute values, e.g.,
attr.source = c('.numberLines', 'startFrom="11"').
These options are mostly useful to HTML output. There are cases in which the attributes may be useful to other output formats, but these cases are relatively rare. The attributes need to be supported by either Pandoc (such as the
.numberLines attribute, which works for both HTML and LaTeX output), or a third-party package (usually via a Lua filter, as introduced in Section 4.20).
It could also be converted to
<div class="className"></div>. You may view the source of the HTML output document to make sure.↩︎