繁体   English   中英

R Shiny:在verbatimTextOuput中编写R代码是否有特殊字体?

[英]R shiny : is there a special font for writing R code in verbatimTextOuput?

我正在写一个Shinyapp,它在verbatimTextOutput环境中显示一些R代码,我想知道是否有一种方法可以在Rstudio显示它时显示该代码(例如,在标签后面加上绿色字体)。

我知道可以用CSS更改字体(即使我不知道怎么做),但是有没有像Rstudio那样自动显示代码的“包”?

这是一个可重现的示例:

library(shiny)

ui <- fluidPage(
  titlePanel(""),
  sidebarLayout(
    sidebarPanel(),
    mainPanel(verbatimTextOutput("base", placeholder = FALSE))
    )
  )

server <- function(input, output) {

  output$base <- renderPrint({
    cat("# I would like this to be written in green (or other color)",
        "library(this could be in blue)",
        sep = "\n")
  })

}

shinyApp(ui = ui, server = server)

我建议像这样对html标记进行硬编码:

library(shiny)

ui <- fluidPage(
  titlePanel(""),
  sidebarLayout(
    sidebarPanel(),
    mainPanel(uiOutput("base", placeholder = FALSE))
  )
)

server <- function(input, output) {

  output$base <- renderUI({
    HTML("<form class = 'well'>
            <p style = 'color: green;'>I would like this to be written in green (or other color)</p>
            <p style = 'color: blue;'>library(this could be in blue)</p>
          </form>")
  })

}

shinyApp(ui = ui, server = server)

您不能完全按照自己的意愿去做,但是有两种解决方案,我希望您会喜欢一种:-)。

您可以使用HTML标签(使用paste0动态分配颜色),也可以使用CSS为您的verbatimOutput设置样式。 不幸的是,两种颜色是不可能的,因为VerbatimOutput无法处理内联CSS。

library(shiny)

ui <- fluidPage(
    tags$head(tags$style(HTML("
                            #base2 {
                              color: blue;
                            }
                            "))),
    titlePanel(""),
    sidebarLayout(
        sidebarPanel(),
        mainPanel(selectizeInput("color", "Colors", choices = c("green", "blue", "red"), selected = "green", multiple = FALSE),
                  uiOutput("base", placeholder = FALSE),
                  tags$br(),
                  verbatimTextOutput("base2"))
    )
)

server <- function(input, output) {

    output$base <- renderUI({
        HTML(paste0('<span style="color:', input$color, '">I would like this to be written in green</span> (or other color)<br>
          <span style="color:blue">library(this could be in blue)</span>'))
    })

    output$base2 <- renderPrint({
        cat("# I would like this to be written in green (or other color)",
            "library(this could be in blue)",
            sep = "\n")
    })

}

shinyApp(ui = ui, server = server)

开发完我的应用程序后,我可以说Stephane Laurent的答案与我想做的最接近(即在闪亮的应用程序中显示反应性R代码)。

ShinyAce软件包确实很有用,您可以在此处找到一些示例( https://trestletech.github.io/shinyAce/ )。

无论如何,谢谢您的回答!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM