Skip Links

Blog

Posts tagged with "dynamic attribute values".

Setting tiles attribute values at runtime

Mark

Mark

14 Jan 2010 10:51

mosaic

It’s quite common to need to set an attribute value at runtime for a web application. Titles are a very common e.g. using a person’s name as the title for their profile page.

We’re currently using tiles for layout management in a GAE4J application so as it took me a little while to decipher the documentation, I thought I’d just write it up quickly here.

The steps are pretty simple:

  • Create an implementation of ViewPreparer
  • Link your ViewPreparer to your tiles definition.

A ViewPreparer is called before a definition is rendered.

Creating a view preparer

You only need to implement the execute method. The execute method gives you access to the TilesRequestContext which you can use to access request or session variables. They are where I would expect you to be pulling your dynamic attribute value from. An example is shown below

public void execute(TilesRequestContext tilesContext, 
    	AttributeContext attributeContext) throws PreparerException {
    	// get the session attributes
    	Map<String, Object> sessionScope = tilesContext.getSessionScope();
    	
    	Survey survey = (Survey) sessionScope.get(BaseServlet.SURVEY_ATTRIBUTE);
    	if (survey != null) {
    		String title = survey.getName();
    		
    		// if a name has been set, show it as the title
    		if (title != null && !title.equals("")) {
    			attributeContext.putAttribute(
    				"title",
    		        new Attribute(title));
    		}
    	}
    }

Linking the ViewPreparer to your tiles definition

Set the preparer attribute on your tiles definition. See the example below.

<definition name="survey" extends="admin" preparer="com.ontruenorth.socrates.view.preparers.SurveyTitlePreparer">
	...
</definition>

Enjoy!

Tagged in: tiles, dynamic attribute values, gaej