Reputation: 807
Below are three files to illustrate my question and the way my program is structured. What I want to do is use the bootstrap card and within it put an R variable (e.g., the result of some calculation). Is there a way I can do that with the HTML in a separate document?
For example, suppose myVariable <- 2^2
is done within the server file and I want the result of that calculation in the object myVariable to be inside the card where I've denoted "put R variable".
Thank you for advice or suggestions.
ui <- fluidPage(
navbarPage(
theme = bs_theme(bootswatch = "flatly"),
title = 'Methods',
tabPanel('One'),
),
mainPanel(
h1('Hello World'),
includeHTML("foo.html")
)
)
library(shiny)
library(bslib)
server <- function(input, output) {
}
<div class="card text-center">
<div class="card-header">
Featured
</div>
<div class="card-body">
<h5 class="card-title">Special title treatment</h5>
<p class="card-text">I want to put an R variable here</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
<div class="card-footer text-muted">
2 days ago
</div>
</div>
Upvotes: 3
Views: 535
Reputation: 84709
You can use renderUI
, in this way there's no need of shinyjs:
library(shiny)
library(bslib)
mycard <- function(x){
sprintf('
<div class="card text-center">
<div class="card-header">
Featured
</div>
<div class="card-body">
<h5 class="card-title">Special title treatment</h5>
<p class="card-text">%s</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
<div class="card-footer text-muted">
2 days ago
</div>
</div>
', x)
}
ui <- fluidPage(
navbarPage(
theme = bs_theme(bootswatch = "flatly"),
title = 'Methods',
tabPanel('One'),
),
mainPanel(
h1('Hello World'),
uiOutput("mycard")
)
)
server <- function(input, output){
output[["mycard"]] <- renderUI({
HTML(mycard(2*2))
})
}
shinyApp(ui, server)
Upvotes: 2
Reputation: 7360
Since the card comes from your custom HTML, not standard card components from Shiny or other Shiny extension packages. We can use shinyjs
package to send the variable to UI and run some simple Javascript to update the value.
library(shiny)
library(bslib)
library(shinyjs)
ui <- fluidPage(
useShinyjs(),
navbarPage(
theme = bs_theme(bootswatch = "flatly"),
title = 'Methods',
tabPanel('One'),
),
mainPanel(
h1('Hello World'),
HTML(
'
<div class="card text-center">
<div class="card-header">
Featured
</div>
<div class="card-body">
<h5 class="card-title">Special title treatment</h5>
<p id="mycard" class="card-text">I want to put an R variable here</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
<div class="card-footer text-muted">
2 days ago
</div>
</div>
'
)
)
)
library(shiny)
library(bslib)
server <- function(input, output) {
observe({
myVariable <- 2^2
runjs(paste0('$("#mycard").text("', myVariable, '")'))
})
}
shinyApp(ui, server)
mycard
so I can easily selected with JS.HTML()
tag, which is the same, you can continue to use your foo.html, but remember to add id="mycard"
to the card.Upvotes: 3