将变量传递到R中的HTML标签中

时间:2019-07-02 11:50:15

标签: html r shiny

我需要在闪亮的应用程序中显示推文,因此我们假设URL在数据框中。 这是我的没有变量的代码:

library(shiny)
runApp(list(
  ui = fluidPage(
    tags$head(
      tags$script("!function(d,s,id){var js,fjs=d.getElementsByTagName(s)    [0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document,'script','twitter-wjs');")
    ),
      mainPanel(
HTML('
<blockquote class="twitter-tweet" data-lang="en"> 

<a href="https://twitter.com/Twitter/status/1144673160777912322">tweet1</a>

</blockquote>
   ') )
  ),
  server = function(input, output, session) {}
))
)

然后我对HTML进行一些更改并传递一个变量

HTML('
<blockquote class="twitter-tweet" data-lang="en"> 

paste0("<a href='",Top5Retweet2[1,3],"'>","tweet","</a>")
</blockquote>
   ')
      ) )

但是我得到了这个错误,我认为是因为引号

Error: unexpected '<' in "<"

此外,我尝试了所有这些操作,但仍未显示任何内容

cat("<a href=\"",Top5Retweet2[1, 3],"\">","tweet","</a>")
cat("<a href=", dQuote(Top5Retweet2[1, 3]) ,">","tweet","</a>")

更新:

runApp(list(
  ui = fluidPage(
    tags$head(
      tags$script("!function(d,s,id){var js,fjs=d.getElementsByTagName(s)    [0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document,'script','twitter-wjs');")
    ),
      mainPanel(
        htmlOutput("tweets_show")

      )
  ),
  server = function(input, output, session) {
    output$tweets_show <- renderUI({
      HTML(
        paste('<blockquote class="twitter-tweet" data-lang="en">',
              paste("<a href=\"",Top5Retweet2[2, 3],"\">","tweet","</a>"),
              '</blockquote>') 
      )
    })

  }
))

任何帮助谢谢

1 个答案:

答案 0 :(得分:1)

?renderUI中,我们可以使用tagList插入多个HTML标签的列表

library(shiny)
runApp(list(
    ui = fluidPage(
      mainPanel(
        htmlOutput("tweets_show")  
      )
    ),
    server = function(input, output, session) {
      tws <- c("https://twitter.com/Twitter/status/1144673160777912322","https://twitter.com/Twitter/status/1144673160777912322","https://twitter.com/Twitter/status/1144673160777912322")
      output$tweets_show <- renderUI({
       tagList(
         tags$head(
          tags$script("!function(d,s,id){var js,fjs=d.getElementsByTagName(s)    [0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document,'script','twitter-wjs');")
        ),
        HTML(
          paste('<blockquote class="twitter-tweet" data-lang="en">',
                paste("<a href=\"",tws,"\">","tweet","</a>"),
                '</blockquote>') 
        ))
      })

    }
  ))