Reputation: 589
When you use inline code in an R Markdown document, the code is evaluated and the output is incorporated into the text. For example,
The sum of 2 and 2 is `r 2+2`.
This will generate the following text in the .nb.html
file:
The sum of 2 and 2 is 4.
That text is not styled or tagged in any way in the HTML output, so there is no way to apply CSS.
But I'd like to be able to see in the HTML document if text appears "as is" or if it was processed through inline code. In other words, I want to know see a difference in the appearance of the number 4 if I write
The sum of 2 and 2 is `r 2+2`.
versus
The sum of 2 and 2 is 4.
Is there any way to do this?
(The use case here is that I have students who are supposed to use inline code in their assignments, but if I'm looking at the .nb.html
file and not the .Rmd
file, I can't tell if they just manually typed in an answer without using code to generate it.)
EDIT: My original question said R Markdown, and there is a good solution to that question below. However, I need this to work in an R Notebook, and it seems that knit_hooks$set
is ignored when creating the HTML file.
Upvotes: 4
Views: 1005
Reputation: 19897
One possible way is using knitr::knit_hooks$set
.
---
title: "Untitled"
author: "Shafayet Khan"
date: "2022-07-31"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
random_class <- paste0("class-", round(runif(1, 200, 2000)))
styleIt <- function(x) {
paste0("<span class='", random_class, "' style=\"color: red;\">", x,"</span>")
}
knitr::knit_hooks$set(inline = styleIt)
```
## R Markdown
### inline code
The sum of 2 and 2 is `r 2+2`
### not inline code
The sum of 2 and 2 is 4.
### Manually styled
The sum of 2 and 2 is <span style="color: red;">4</span>
When rendered, it looks like
Now note that the students always can use the span
tag to get the same color as the inline code, so to make a difference, I have used a randomly generated class and used that for inline code, so when you have the HTML file, span
tag for an inline code should have a randomly generated class name like class-672
while manually typed and colored code will unlikely have that same class name. Hope this helps.
Upvotes: 0