I think that displaying your Twitter posts on your website is a wonderful way to show people in-time news. This feature can be very useful for your project. Because it can can inspire your website’s visitors to follow you on Twitter. I am going to create simple script which loads twitter posts and renders into HTML format using JsRender jQuery library. Everything is on the client side.
Let’s start coding !
Step 1. HTML
Our HTML markup is very easy:
04 | < meta charset = "utf-8" /> |
05 | < title >My twitter posts | Script Tutorials</ title > |
06 | < link href = "css/main.css" rel = "stylesheet" type = "text/css" /> |
09 | google.load("jquery", "1.7.1"); |
11 | < script type = "text/javascript" src = "js/jsrender.js" ></ script > |
12 | < script type = "text/javascript" src = "js/main.js" ></ script > |
14 | < script id = "twitterTemplate" type = "text/x-jsrender" > |
17 | < p >< b >{{:user.name}}:</ b > {{:text}} < span >(on: {{:created_at}})</ span ></ p > |
18 | < a href = "https://twitter.com/{{:user.screen_name}}" >< img src = "{{:user.profile_image_url}}" alt = "{{:user.name}}" /></ a > |
24 | < div class = "content-main" > |
25 | < h2 class = "content-header" >Tweets</ h2 > |
26 | < div class = "content-body" id = "results" ></ div > |
You can see here a template for twitter posts (twitterTemplate) for JsRender, and a simple container for future posts (<div class=”content-body” id=”results”></div>)
Step 2. CSS
Now, we have to prepare CSS stylesheet for our demonstration:
02 | -webkit-border-radius: 6px ; |
03 | -moz-border-radius: 6px ; |
05 | background-color : #FFFFFF ; |
06 | border : 1px solid #E8E8E8 ; |
11 | -webkit-border-radius: 5px 5px 0 0 ; |
12 | -moz-border-radius: 5px 5px 0 0 ; |
13 | border-radius: 5px 5px 0 0 ; |
14 | border-bottom : 1px solid #E8E8E8 ; |
19 | border-bottom : 1px solid #E8E8E8 ; |
24 | .content-body > div .elem { |
27 | .content-body > div img { |
33 | .content-body > div p { |
38 | .content-body > div span { |
Step 3. JavaScript
And finally – a very small Javascript:
02 | function displayTweets(data) { |
05 | $( '#twitterTemplate' ).render(data) |
09 | $(window).load( function () { |
11 | var name = 'AramisGC' ; |
15 | var ts = document.createElement( 'script' ); |
16 | ts.type = 'text/javascript' ; |
Basically, we have to prepare extra Script which requires our last tweets (timeline) in JSON format from twitter website. And then, we just should pass received results into our ‘twitterTemplate’ template to render the results.
Important: Due Twitter API v1.0 is deprecated, we have to use updated URL to obtain user timeline. Pay attention to line 24 in main.js file.
[sociallocker]
[/sociallocker]
Conclusion
I hope that everything is clean in today’s code. If you have any suggestions about further ideas for articles – you are welcome to share them with us. Good luck in your work!