Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
306 views
in Technique[技术] by (71.8m points)

r - Change CSS properties based on shiny input

In my app, CSS properties are in a separate file and included in the ui via includeCSS('./www/styles.css').

Is it possible to dynamically change the font-family property based on the value of an input?

e.g. ui contains:

selectInput(inputId = 'selected_language', label = 'Choose language', choices = c('lao', 'english'), selected = 'english')

When 'lao' is selected, body { font-family: Phetsarath OT; } is used while if 'english' is selected body { font-family: Arial, Helvetica, sans-serif; } is used.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could include the css part in tags$style and put it within renderUI() on the server side.

The easiest way would be put the rest of the css on the server side as well, but you could also read from the styles.css file, see below.

Reproducible example:

library(shiny)

# Simulating a styles.css file
css_content <- "
h4 {
  font-family: 'Lobster', cursive;
  font-weight: 500;
  line-height: 1.1;
  color: #48ca3b;
}
"

writeLines(text = css_content, con = "styles.css")

css <- readLines(con = "styles.css") %>% 
  paste(collapse = "
")


ui <- fluidPage(
  selectInput(inputId = 'selected_language', label = 'lang', choices = c('lao', 'english'), selected = 'english'),
  uiOutput("css_style"),
  h3("one"),
  h4("two"),
  h5("three")
)

server <- function(input, output, session) {
  
  style <- reactive({
    ifelse(
      test = input$selected_language == "lao",
      yes = "body { font-family: Phetsarath OT; }",
      no = "body { font-family: Arial, Helvetica, sans-serif; }"
    )
  })
  
  output$css_style <- renderUI({
    tags$head(
      tags$style(
        HTML(
          paste0(c(style(), css), collapse = "
")
        )
      )
    )
  })
}

shinyApp(ui, server)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...