The Grails way #0: Simple Twitter TagLib

Posted by Ktoso on 25/05/2010 – 16:33

Let’s skip the introduction of taglibs, (since anyone knows what they are), and get to the code really quickly! If you’ve seen netbeans.edu.pl you probably noticed the twitter part on the right. As twitter’s API is really simple to use, one could implement this on ones own, but why do so if we’re in the Grails -> Groovy -> Java world, where there are amazing libraries for most things.

I used 2 libs to create this tag:

Anyways, first the source of the actuall taglib. We simply call the methods, get the response fill out the content of the tag with the variables we got:

package pl.project13
  1.  
  2. import com.twitter.Autolink
  3. import twitter4j.*
  4.  
  5. class TweetsTagLib {
  6.   static namespace = 'tweets'
  7.  
  8.   /**
  9.    * Performs an twitter search and displays the result as an
  10.    */
  11.   def fromSearch = {attrs, body ->
  12.     Twitter twitter = new TwitterFactory().getInstance()
  13.     Query query = new Query(attrs.query)
  14.  
  15.     QueryResult result = twitter.search(query)
  16.  
  17.     def tweetz = result.tweets.subList(0, Integer.parseInt(attrs.count))
  18.     tweetz.each {Tweet tweet ->
  19.       Autolink parser = new Autolink()
  20.       tweet.text = parser.autoLink(tweet.text)
  21.  
  22.       pageScope.tweet = tweet
  23.       out < < body(tweet)
  24.     }
  25.   }
  26.  
  27.   //some other stuff…
  28.  
  29. }

Super easy, ain’t it? More stuff about taglibs in grails can be found here. Now let’s go over to our view and see how to use this taglib – it’s (once again) amazingly simple:

  1. <g :set var="query" value="netbeans"/>
  2.  
  3. <h3>Twitter #${query}</h3>
  4. <div id="twitter" class="menubox">
  5.   <ul>
  6.     <tweets :fromSearch query="#${query}" count="8">
  7.       <li>
  8.         <a href="http://www.twitter.com/${it.fromUser}" target="_blank" class="twitter-author">
  9.           <img src="${it.profileImageUrl}" alt="${it.fromUser}" title="${it.fromUser}" style="float:left; padding:2px; width:25px; height:25px"/>
  10.           %{–${it.fromUser}:–}%
  11.         </a>
  12.         ${it.text}<br />
  13.         <span style="font-size:0.75em" class="twitter-date">${it.createdAt}</span>
  14.       </li>
  15.     </tweets>
  16.   </ul>
  17.  
  18.   &#187;&nbsp;<a href="http://twitter.com/#search?q=${query}" target="_blank">więcej</a>
  19.  
  20. </div>

All we need to do here, is set an variable thanks to some nice GSP tag, and then use it to query and echo our data the taglib is supplying us with. Note that the tweets:fromSearch acts like an foreach – no need for any extra loops here :-) That’s just a very simple tag but it’s quite nice to use, hope you enjoied it and will be more than happy to see the sources of netbeans.edu.pl published on github soon… :-)

Tags: , , , , , , ,

This post is under “coding, java” and has no respond so far.

Post a reply