The Grails way #0: Simple Twitter TagLib
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:
- twitter4j – a very good twitter client library (java, even works on android)
- twitter-text-java – the official library for parsing plaintext to produce valid @ and # links, more information about it can be found on github or http://engineering.twitter.com/2010/02/introducing-open-source-twitter-text.html
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:
-
-
import com.twitter.Autolink
-
import twitter4j.*
-
-
class TweetsTagLib {
-
static namespace = 'tweets'
-
-
/**
-
* Performs an twitter search and displays the result as an
-
*/
-
def fromSearch = {attrs, body ->
-
Twitter twitter = new TwitterFactory().getInstance()
-
Query query = new Query(attrs.query)
-
-
QueryResult result = twitter.search(query)
-
-
def tweetz = result.tweets.subList(0, Integer.parseInt(attrs.count))
-
tweetz.each {Tweet tweet ->
-
Autolink parser = new Autolink()
-
tweet.text = parser.autoLink(tweet.text)
-
-
pageScope.tweet = tweet
-
out < < body(tweet)
-
}
-
}
-
-
//some other stuff…
-
-
}
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:
-
<g :set var="query" value="netbeans"/>
-
-
<h3>Twitter #${query}</h3>
-
<div id="twitter" class="menubox">
-
<ul>
-
<tweets :fromSearch query="#${query}" count="8">
-
<li>
-
<a href="http://www.twitter.com/${it.fromUser}" target="_blank" class="twitter-author">
-
<img src="${it.profileImageUrl}" alt="${it.fromUser}" title="${it.fromUser}" style="float:left; padding:2px; width:25px; height:25px"/>
-
%{–${it.fromUser}:–}%
-
</a>
-
${it.text}<br />
-
<span style="font-size:0.75em" class="twitter-date">${it.createdAt}</span>
-
</li>
-
</tweets>
-
</ul>
-
-
» <a href="http://twitter.com/#search?q=${query}" target="_blank">więcej</a>
-
-
</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… :-)


Post a reply