rr-markdown

Updating title in Rmarkdown dynamically


In my flexdashboard, I would like to set the windows title (that is seen in the browser tab) dynamically.

The following mre works. But, when I change the params, I have to render the document two times to see the result in the windows title.

Is there a way to do it in one go? I tried cache=FALSE in the second chunk but that did not help.

---
title: 'Status: `r sprintf("%.0f%%", progress*100)`'
params:
   current_page: 27
   total_pages: 79
output:
   flexdashboard::flex_dashboard: default
   html_document: default
---

```{r global, include=FALSE}
library(bslib)
```

```{r, cache = FALSE}
progress <- with(params, current_page / total_pages)
bslib::value_box(title="Status", value=sprintf("%.0f%%", progress*100))
```

Solution

  • You could use Javascript and {htmltools} to update the content:

    ## load other libraries
    library(htmltools)
    

    put this snippet someplace after the calculation of progress:

    ```{r, echo = FALSE}
    progress_formatted <- sprintf("%.0f%%", progress*100)
    tags$script(sprintf("document.querySelector('span.navbar-brand').innerHTML = 'Status: %s'", progress_formatted))
    ```
    

    However, I think the way to go is to calculate the progress in a/the separate script from which you render the Rmd-template, and hand over the progress together with the other params (current_page and total_pages). Something along the lines of:

    total_pages <- 42
    
    Map(1:total_pages,
        f = \(current_page){
           rmarkdown::render('path/to/your_template.Rmd',
                            ## options,
                            params = list(total_pages = total_pages,
                                          current_page = current_page,
                                          progress = current_page / total_pages
                            )
                            
        })