How can I embed a twitter timeline in a Shiny app

2020-03-19 02:57发布

I am keen to embed a twitter timeline as part of a Shiny App. I have got the relevant code snippet

<a class="twitter-timeline" href="https://twitter.com/pssGuy/timelines/524678699061641216" 
data-widget-id="524686407298596864">Soccer</a>

<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");</script>

I have created a twitter.js file (the above minus the script tags ) and a ui.R as below

library(shiny)
shinyUI(fluidPage(

tags$head(includeScript("twitter.js")),

titlePanel(""),

sidebarLayout(
sidebarPanel(
),

mainPanel(
  a("Soccer", class="twitter-timeline",    href="https://twitter.com/pssGuy/timelines/524678699061641216",  data-widget-id="524686407298596864")

)
)
))

This produces an error

ERROR: C:\Users\pssguy\Documents\R\testGoogleTwitter/ui.R:19:124: unexpected '='
18:     mainPanel(
19:       a("Soccer", class="twitter-timeline",     href="https://twitter.com/pssGuy/timelines/524678699061641216",  data-widget-id=

If I omit the data-widget-id="524686407298596864", I get a link which, when clicked on, opens a browser window with the correct timeline

One thing I have noticed is that the script given is not quite the same as that in twitters development tutorial https://dev.twitter.com/web/embedded-timelines

<script type="text/javascript">
window.twttr = (function (d, s, id) {
var t, js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id; js.src= "https://platform.twitter.com/widgets.js";
fjs.parentNode.insertBefore(js, fjs);
return window.twttr || (t = { _e: [], ready: function (f) { t._e.push(f) } });
}(document, "script", "twitter-wjs"));
</script>

TIA

1条回答
放荡不羁爱自由
2楼-- · 2020-03-19 03:14

You need to quote data-widget-id as it is not a syntactically valid name:

> make.names("data-widget-id")
[1] "data.widget.id"

So the following should work:

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");')),
  titlePanel(""),
  sidebarLayout(
    sidebarPanel()
    , mainPanel(
      a("Soccer", class="twitter-timeline"
        , href = "https://twitter.com/pssGuy/timelines/524678699061641216"
        , "data-widget-id" = "524686407298596864")
    )
  )
)
, server = function(input, output, session){

}
)
)

enter image description here

查看更多
登录 后发表回答