Title each code chunk with the language in that code chunk

I am writing a manual for some work stuff in Quarto. Some of the pages will include both R and Python. I am wondering if there is a way to automatically label each code chunk with the language in that code chunk. I am currently trying it manually via title and #| label: R but neither are outputting anything.

```{python, title="Python"}

1 + 1
```

```{r, title="R"}
#| label: R

1 + 1
```

As you can see below, neither actually appear on the rendered HTML.

I would prefer each cell to have the language labelled something like this:

The exact location within the cell does not matter to me.

Automated would be preferred, but manual is completely acceptable as well.

I am using RStudio with R version 4.4.1, reticulate version 1.38.0, and Python 3.12.4.

I have also posted this question on stackoverflow.

Thanks!

Hi, I believe you could also embed the snippets in tabs unless you need to see both at the same time:

A nice suggestion. We're seeing a lot of requests for customising Quarto templates at work at the moment.

We can achieve something like this with CSS since you are doing HTML output. But as a warning, this method would not be considered friendly to those with accessibility needs because adding text through CSS means a screen reader will not see it.

---
title: "quarto_lang_label"
format: 
  html:
    css: language_code.css
---

## Basic code chunks

In python:

```{python}
1 + 1
```

In R:

```{r}
1 + 1
```

Some more R:

```{r}
f1 = function(x) {
  return(x * x + x)
}
```

You'll have to add classes to have the label for other languages: 
```{js}
foo = document.getElementById("foo");
```

language_code.css

code.sourceCode.python::before {
  content: "python";
}

code.sourceCode.r::before {
  content: "R";
}

code.sourceCode.python::before, code.sourceCode.r::before {
  position: absolute;
  background-color: black;
  color: white;
  top: 0;
  right: 0;
  padding: 0 3px 0 4px;
  border-radius: 0 0 0 6px;
}

Watch out for long first lines in code chunks, as they will be blocked by the language label.

1 Like

I believe we had some questions like this our Discussion board. Example of one:

I think there are others to be found there. Basically, you can use a Lua filter to try to this.

Otherwise, you can also just leverage the tabset feature of Quarto if you always have both languages.

Hope it helps

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.