我试图将随机生成的字符串推送到UI上的textarea。 HTML / Shiny / JS新手,但我知道一些基础知识。
我的最终目标是使用CodeMirror(Whole download)或ShinyAce编辑器类来向textarea添加语法高亮,但我无法将服务器中的字符串输出到textarea。我希望在textStringToDisplay
中推送某个R代码并需要语法高亮。
请将以下文件放在app.R的www文件夹中:
如果您需要更多信息或我是否应该重新措辞,请告诉我。提前谢谢。
library(shiny)
if (interactive()) {
ui <- shinyUI(
fluidPage(
tags$head(tags$title("Title"),
tags$link(rel = "stylesheet", href = "codemirror.css"),
tags$link(rel = "stylesheet", href = "cobalt.css"),
tags$script(src = "codemirror.js"),
tags$script(src = "r.js")
),
tags$textarea(id="textBox", name = "Feedback", textOutput(outputId = "textStringToDisplay")),
tags$script(
'var editorR = CodeMirror.fromTextArea(textBox, {
mode: "r",
lineNumbers: true,
smartindent: true
});
editorR.setOption("theme", "cobalt");
editorR.setSize("50%","100%");')))
server <- function(input, output){
output$textStringToDisplay <- renderText(paste0(sample(letters,15),collapse = ""))
}
shinyApp(ui = ui, server = server)
}
答案 0 :(得分:0)
您好我已经注释掉了您的css和java脚本,因为我不知道问题所在。您的问题与此问题相同
How to create a variable hyperlink in an R Shiny App
以下是您的代码的工作版本
library(shiny)
if (interactive()) {
ui <- shinyUI(
fluidPage(
tags$head(tags$title("Title")
# tags$link(rel = "stylesheet", href = "codemirror.css"),
# tags$link(rel = "stylesheet", href = "cobalt.css"),
# tags$script(src = "codemirror.js"),
# tags$script(src = "r.js")
),
uiOutput(outputId = "textStringToDisplay")
# tags$script(
# 'var editorR = CodeMirror.fromTextArea(textBox, {
# mode: "r",
# lineNumbers: true,
# smartindent: true
# });
# editorR.setOption("theme", "cobalt");
# editorR.setSize("50%","100%");')
))
server <- function(input, output){
output$textStringToDisplay <- renderUI(
tags$textarea(id="textBox", name = "Feedback", paste0(sample(letters,15),collapse = "")))
}
shinyApp(ui = ui, server = server)
}
答案 1 :(得分:0)
这是我的最终实施。要感谢@Bertil关于renderUI
的建议。不得不使用shinyjs
包和runjs
函数来运行JS脚本。此外,它仅适用于与事件配对(如单击按钮)。在应用加载时不知道如何触发它(稍后会发布另一个关于此的问题)。
library(shiny)
library(shinyjs)
if (interactive()) {
ui <- shinyUI(
fluidPage(
useShinyjs(),
tags$head(tags$title("Title"),
tags$link(rel = "stylesheet", href = "codemirror.css"),
tags$link(rel = "stylesheet", href = "cobalt.css"),
tags$script(src = "codemirror.js"),
tags$script(src = "r.js")
),
actionButton("btn1","Click to see code"),
uiOutput(outputId = "textStringToDisplay")))
server <- function(input, output){
output$textStringToDisplay <- renderUI(
tags$textarea(id="textBox", name = "Feedback", paste0(sample(letters,15),collapse = "")))
ButtonPressCounter <- 0
observeEvent(input$btn1,
{
ButtonPressCounter <<- ButtonPressCounter + 1 # Need it to happen only once
if(ButtonPressCounter <= 1){
shinyjs::runjs(
'var editorR = CodeMirror.fromTextArea(textBox, {
mode: "r",
lineNumbers: true,
smartindent: true});
editorR.setOption("theme", "cobalt");
editorR.setSize("100%","100%");')
}
})
}
shinyApp(ui = ui, server = server) }