Search code examples
r-markdownknitrpandoc

Add class to <img>-tag generated by knitr (Rmd)


I write a R Notebook (Rmd) that I want to render as HTML.

    ::: { .mycls }

    ```{r dev="svg", fig.dim=c(8,6), out.width="100%"}
    ggplot(data.frame(x=rnorm(40, 5, 8),
                      y=rnorm(40, 2, 1),
                      group=factor(sample(c(1,2), 40, TRUE, c(0.3, 0.7))))) +
    geom_point(aes(x=x, y=y, color=group))
    ```
    :::

The corresponding html snippet looks like this (no working example!, truncated!):

<div class="mycls">
  <div class="row">
    <div class="col-md-12">
      <button type="button" ...>
        <span>Show</span>
      </button>
    </div>
  </div>
  <div class="collapse r-code-collapse" id="rcode-643E0F362">
    <pre class="r">
      <code class="hljs">... the code from above ...</code>
    </pre>
  </div>
  <p>
    <img src="data:image/svg+xml;base64,<...>" width="100%">
  </p>
</div>

I want to add functionality to the figure (<img>-tag) with JS and CSS, so it would be great, to have a class on it. The closest thing I found was adding the

::: { .mycls }

:::

to create the enclosing <div class="mycls>-tag. Then I could search for the <img>-tag within. However I'd prefer a solution, where I can have the class-attribute set directly in the <img>-tag.

I was trying to add options to the chunk:

```{r dev="svg", fig.dim=c(8,6), out.width="100%", class.img="imgcls", fig.class="imgcls"} 
   ...
```

since it seems like, you could specify tons of attributes there, but I didn't find the right one.


Solution

  • The correct chunk option is out.extra (bad naming, I admit), e.g., out.extra = 'class="mycls"'.