ijlyttle / bsplus

Shiny and R Markdown addons to Bootstrap 3
http://ijlyttle.github.io/bsplus/
Other
146 stars 21 forks source link

How to create bs_modal() in a loop in rmarkdown? #92

Closed fmmattioni closed 3 years ago

fmmattioni commented 3 years ago

Hi @ijlyttle,

Thanks again for this great package!

I have been wondering one thing: what is the right way to create several bsplus::bs_modal() in a loop in rmarkdown? My approach using lapply works quite well in shiny, but I still haven't found a way to make this work in my .Rmd file.

Minimal .Rmd reprex with desired outcome:

---
title: "Untitled"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(magrittr)
bsplus::bs_modal(id = paste0("button_", 1), title = paste0("modal ", 1), body = NULL)
bsplus::bs_modal(id = paste0("button_", 2), title = paste0("modal ", 2), body = NULL)
bsplus::bs_button("Modal 1") %>% 
  bsplus::bs_attach_modal("button_1")
bsplus::bs_button("Modal 2") %>% 
  bsplus::bs_attach_modal("button_2")

Minimal `.Rmd` reprex with the approach I am using but it is not working:

````markdown
---
title: "Untitled"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(magrittr)
lapply(1:2, function(i) {
  bsplus::bs_modal(id = paste0("button_", i), title = paste0("modal ", i), body = NULL)
})
lapply(1:2, function(i) {
  bsplus::bs_button(paste0("Modal ", i)) %>% 
    bsplus::bs_attach_modal(paste0("button_", i))
})


Any thoughts?

Thanks in advance!
Felipe
fmmattioni commented 3 years ago

My bad, I didn't realize I should be using tagList().

Solution:

---
title: "Untitled"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(magrittr)
htmltools::tagList(lapply(1:2, function(i) {
  bsplus::bs_modal(id = paste0("button_", i), title = paste0("modal ", i), body = NULL)
}))
htmltools::tagList(lapply(1:2, function(i) {
  bsplus::bs_button(paste0("Modal ", i)) %>% 
    bsplus::bs_attach_modal(paste0("button_", i))
}))