Techminded

Transparent blocks in PlayFramework

Comparing to other comprehensive Web frameworks PlayFramework's tags are not really good to make tranparent site blocks because they force developer to put storage data via renderArgs using controller hook method (annotated with @Before) that is unflexible or include Java code into template that is just worst idea to develop webinterface. Fortunatly framework has a way to implement tags as Java FastTags class child.

You may use Yabe (from official tutorial) to try things. To make our true MVC block we will create a class BlockLatestPosts in tags package as follows:

import groovy.lang.Closure;
import models.Post;
import org.apache.commons.lang.StringUtils;
import play.templates.FastTags;
import play.templates.GroovyTemplate.ExecutableTemplate;

import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@FastTags.Namespace("block")
public class BlockLatestPosts extends FastTags {

    public static void _latest_posts(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) {
        List<Post> latestPosts = Post.find("order by postedAt asc").fetch(5);
        body.setProperty("latestPosts", latestPosts);
        body.call();
    }
}

/app/tags/BlockLatestPosts.java

Now lets create template file:

#{block.latest_posts}
    <h3>Latest posts:</h3>
    #{list items:latestPosts, as:'post'}
            #{a @Posts.show(post.id)}${post.title}#{/a}<br />
    #{/list}
#{/block.latest_posts}

/app/views/Posts/BlockLatestPosts.html

Now we can use block anywhere by including template as follows:

#{include 'Posts/BlockLatestPosts.html' /}

Some additional links:
http://playframework.wordpress.com/2010/11/26/fasttags-in-play/
http://groups.google.com/group/play-framework/browse_thread/thread/579dd31591fc4f87/1fcc16eb4e2056a4?lnk=gst&q=FastTags

Comments