Back

Load Latest Tweet (Twitter) into Page

Description

This code will pull in the latest tweet from any Twitter account and display it in your page. It also does the work of converting addresses, hash tags and mentions into clickable links.

Code

${esc.hash}set(${esc.dollar}startWithUser = false)
${esc.hash}set(${esc.dollar}twitterUsername = "okchristian")

${esc.hash}set(${esc.dollar}path = "http://twitter.com/statuses/user_timeline/${esc.dollar}!{twitterUsername}.rss")
${esc.hash}set(${esc.dollar}_dummy = ${esc.dollar}xmltool.read(${esc.dollar}path))
${esc.hash}set(${esc.dollar}twitterData = ${esc.dollar}xmltool.parse(${esc.dollar}_dummy))
${esc.hash}set(${esc.dollar}twitterDesc = ${esc.dollar}twitterData.find('channel/item/description'))


${esc.hash}set(${esc.dollar}latestTweet = ${esc.dollar}twitterDesc.get(0).toString())

${esc.hash}${esc.hash} Strip off beginning username if it's not wanted
${esc.hash}if(${esc.dollar}startWithUser != true)
	${esc.hash}set(${esc.dollar}latestTweet = ${esc.dollar}latestTweet.replaceAll("(?i)${esc.dollar}!{twitterUsername}: ",""))
${esc.hash}end

${esc.hash}${esc.hash} Strip off <description> tags
${esc.hash}set(${esc.dollar}latestTweet = ${esc.dollar}latestTweet.replaceAll("<\/?description>",""))

${esc.hash}${esc.hash} Replace URL text with an actual link
${esc.hash}set(${esc.dollar}latestTweet = ${esc.dollar}latestTweet.replaceAll("[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+","<a href='${esc.dollar}0' target='_blank'>${esc.dollar}0</a>"))

${esc.hash}${esc.hash} Replace "${esc.hash}whatever" with a link to "http://twitter.com/search?q=%23whatever"
${esc.hash}set(${esc.dollar}latestTweet = ${esc.dollar}latestTweet.replaceAll("(?<=${esc.hash})((\w+))","<a href='http://twitter.com/search\?q=%23${esc.dollar}0' target='_blank'>${esc.dollar}0</a>"))

${esc.hash}${esc.hash} Replace "@whoever" with a link to "http://www.twitter.com/whoever"
${esc.hash}set(${esc.dollar}latestTweet = ${esc.dollar}latestTweet.replaceAll("(?<=@)((\w+))","<a href='http://twitter.com/${esc.dollar}0' target='_blank'>${esc.dollar}0</a>"))
 
	<h2>@<a href='http://twitter.com/${esc.dollar}!{twitterUsername}' target='_blank'>${esc.dollar}!{twitterUsername}</a> Twitter</h2> 
	<p>${esc.dollar}!{latestTweet}</p>

Have you created code you'd like to share with the dotCMS community?

Share your code Become a Contributor