tirsdag 22. februar 2011

play framework, showing gravatars

Gravatar enables you to show a picture of a person, as long as you have their email-address, and they are registered at gravatar. But you have to do some work :)

So this post is about showing gravatars in play and how we did it when we had a lot of them.
So our stack for this example is jquery and the play! framework v1.1 (using grails templating).

So first the hashing method for getting the gravatar hash. We kept it on the model, but you can also put it in your controller if you have usage beyond the domain.

public static String gravatarhash(String gravatarId){
    if(gravatarId != null)
        return Codec.hexMD5(gravatarId.toLowerCase().trim());
     return null;
}

You call it from the html-file like this;

${models.Person.gravatarhash(person?.email).raw()}

where person in this case is a person with an email attribute populated from a controller.

So that's the hash that gravatar needs. If you have an email registered in gravatar and hash it using the method previosly specified, you ought to get a nice picture out with an img-tag

<img src="http://www.gravatar.com/avatar/${models.Person.gravatarhash(person.email).raw()}"/>
(If there is no email registered at gravatar, it will use a defaulted image. A default you can tweak, just check out their website).

So first off, if you have hundreds of gravatars; you don't put your gravatar url in a img-tag. The general browser will look at that as a resource it has to get on page load. Even with http caching, you don't want to load more resources than the user needs.

So in our case we had a button, and on the push of that button we want to show some pictures. We don't want it to take a long time to get in to the page initially, so what do we do? We load the images with javascript, and don't do it before the user pushes the button.

So we did something like this;
<a href="javascript" onclick="$('people').html('#{list items:people, as:'person' }<img src= quot;http://www.gravatar.com/avatar/${models.Person.gravatarhash(person.email).raw()}quot; alt=quot;${person.name}quot;/>#{/list}');$('people').toggle();">show me a hundred pictures!</a>

<div id="people" style="display:none"></div>


So now go out and add some pictures to your website!

0 kommentarer:

 
 
Copyright © >> /dev/null
Blogger Theme by BloggerThemes Design by Diovo.com