Interface XTemplates
-
- All Known Subinterfaces:
BluePlainTabPanelAppearance.PlainTabPanelTemplates
,BluePlainTabPanelBottomAppearance.PlainTabPanelBottomTemplates
,BlueTabPanelBottomAppearance.BottomTemplate
,BoxLayoutDefaultAppearance.BoxLayoutTemplate
,BoxStatusBaseAppearance.BoxTemplate
,ButtonCellDefaultAppearance.ButtonCellTemplates
,ButtonGroupBaseAppearance.GroupTemplate
,CheckBoxColumnDefaultAppearance.CheckBoxColumnTemplates
,ColorPaletteBaseAppearance.BaseColorPaletteTemplate
,ColumnHeaderDefaultAppearance.ColumnHeaderTemplate
,ContentPanelBaseAppearance.ContentPanelTemplate
,CssFloatLayoutDefaultAppearance.CssFloatLayoutTemplate
,DivFrame.Template
,ErrorTipDefaultAppearance.ErrorTipTemplate
,FieldLabelDefaultAppearance.FieldLabelTemplate
,FieldSetDefaultAppearance.Template
,FileUploadDefaultAppearance.FileUploadTemplate
,FramedPanelBaseAppearance.FramedPanelTemplate
,GrayPlainTabPanelAppearance.PlainTabPanelTemplates
,GrayPlainTabPanelBottomAppearance.PlainTabPanelBottomTemplates
,GrayTabPanelBottomAppearance.BottomTemplate
,GridBaseAppearance.GridTemplates
,GroupingViewDefaultAppearance.DefaultHeaderTemplate
,HeaderDefaultAppearance.Template
,IconButtonDefaultAppearance.Template
,InfoDefaultAppearance.Template
,Insert.DefaultInsertAppearance.Template
,LabelToolItemDefaultAppearance.Template
,Layer.LayerTemplates
,Layer.LayerTemplatesIe
,Layer.ShimTemplates
,Mask.MessageTemplates
,MenuBaseAppearance.BaseMenuTemplate
,MenuItemBaseAppearance.MenuItemTemplate
,NestedDivFrame.Template
,PortalLayoutDefaultAppearance.PortalLayoutTemplate
,ProgressBarDefaultAppearance.ProgressBarTemplate
,RowEditorDefaultAppearance.Template
,SeparatorMenuItemBaseAppearance.SeparatorMenuItemTemplate
,SeparatorToolItemDefaultAppearance.Template
,SliderHorizontalBaseAppearance.SliderHorizontalTemplate
,SliderVerticalBaseAppearance.SliderVerticalTemplate
,StatusDefaultAppearance.Template
,StatusProxyBaseAppearance.StatusProxyTemplates
,TableFrame.Template
,TabPanelBaseAppearance.ItemTemplate
,TabPanelBaseAppearance.Template
,TipDefaultAppearance.TipDefaultTemplate
,ToolTipConfig.ToolTipRenderer<T>
,ViewportDefaultAppearance.ViewportTemplate
public interface XTemplates
A tag interface for declaring methods that accept objects and convert them into HTML based on an associated template. Methods returnSafeHtml
instances which can be used in many GWT and GXT widgets to render content. XTemplates support a variety of features to make it easy to generate content, including:- Reading properties and nested properties
- Formatting data into strings
- Collection and Array iterating, applying sub templates to each item
- Conditional support, including the ability to call other Java methods that return boolean
- Basic math and expression support
Declaring a Template
Templates are declared by creating a new interface that extends
XTemplate
, or by extending another interface that extendsXTemplate
. Instances can then be created by invokingGWT.create
on the template class, and then methods can be invoked.Template method content is created in one of two ways: either by declaring the template content in the
@XTemplate
annotation, or by creating a new html file and pointing the@XTemplate
annotation at that file.public interface SampleXTemplates extends XTemplates { @XTemplate("<div>Hello, {name}!</div>") SafeHtml hello(String name); @XTemplate(source="hello.html") SafeHtml helloExternal(String name); } protected SampleXTemplates tpl = GWT.create(SampleXTemplates.class);
In this example,
tpl.hello("test")
would return aSafeHtml
instance representing the html <div>Hello, test!<div> whiletpl.hello("test")
would have its content depend on the template defined in the filehello.html
in the same package.Reading Properties
This is the data used for reference in each code sample:
public class Kid { public Kid(String name, int age) ... public String getName() ... public int getAge() ... } public class Person { public Person(String name, String company, String product, String location) ... public String getName() ... public String getCompany() ... public String getProduct() ... public String getLocation() ... public List<Kid> getKids() ... public void setKids(List<Kid> kids) ... } final Person person = new Person("John Doe", "ACME Widget Co.", "Widgets", "Anytown, USA"); List<Kid> kids = new ArrayList<Kid>(); kids.add(new Kid("Noah", 4)); kids.add(new Kid("Emma", 2)); kids.add(new Kid("Liam", 1)); person.setKids(kids);
Properties are read by naming the object or property to read in
{ ... }
brackets in the template body. In the main template (not in a<tpl for="...">
tag) these will be scoped based on the arguments to the template. If there is only one argument, the argument may be named, or properties may be referred to directly. If there are multiple arguments, they must be named.interface ReadingPropertiesTemplates extends XTemplates { @XTemplate("Hello, {name}, from {person.location}") // either works SafeHtml oneArgument(Person person); @XTemplate("Hello, {one.name}, {two.name}, and {three.name}!") SafeHtml twoArguments(Kid one, Kid two, Kid three); } ReadingPropertiesTemplates tpl = GWT.create(ReadingPropertiesTemplates.class); SafeHtml parentContent = tpl.oneArgument(person); SafeHtml childrenContent = tpl.twoArguments(person.get(0), person.get(1), person.get(2));
Nested properties are read by separating each getter or method call with a '
.
'. Properties are most often read from getter methods, but can also be read from zero-arg methods by using their full name. As a result of this, the size of the list retrieved fromPerson.getKids()
can be expressed askids.size
:interface PersonWithKidsTemplate extends XTemplates { @XTemplate("{name} has {kids.size} children") SafeHtml renderChildCount(Person p); } PersonWithKidsTemplate tpl = GWT.create(PersonWithKidsTemplate.class); SafeHtml content = tpl.renderChildCount(person);
Formatting Data Into Strings
Values can be formatted using the following syntax:
{value:formatName}
- no format param{value:formatName(format)}
- with format param
Built-in formats:
date(format)
- format syntax uses GWT DateTimeFomat (example:{mydate:date("m/d/yyyy")})
number(format)
- format syntax uses GWT NumberFormat (example:{mynumber:number("0000.0000")})
currency
- no parametersscientific
- no parametersdecimal
- no parameters
Additional formatters can be created and registered when creating an XTemplate. They can be declared on any class - when an XTemplates type is declared, it, and all parents will be checked for formatters to use. Formatters can be redeclared when a type is extended - the type closest to the final type will override other formatters.
Collections and Arrays
The tpl tag and the for operator are used to process the provided data object:
- If the value specified in for is an array, it will auto-fill, repeating the template block inside the tpl tag for each item in the array.
- If for="." is specified, the data object provided is examined.
- While processing an array, the special variable {#} will provide the current array index + 1 (starts at 1, not 0).
<tpl for=".">...</tpl> // loop through array at root node <tpl for="foo">...</tpl> // loop through array at foo node <tpl for="foo.bar">...</tpl> // loop through array at foo.bar node
Using the sample data above:
interface KidListTemplate extends XTemplates { @XTemplate("<p>Kids: " + "<tpl for='.'>" + // process the data.kids node "<p>{#}. {name}</p>" + // use current array index to autonumber "</tpl></p>") SafeHtml listKids(List<Kid> kids); } KidListTemplate tpl = GWT.create(KidListTemplate.class); SafeHtml content = tpl.listKids(person.getKids()); // pass the kids property of the data object
An example illustrating how the for property can be leveraged to access specified members of the provided data object to populate the template:
interface NestedListTemplate extends XTemplates { @XTemplate("<p>Name: {name}</p>" + "<p>Title: {title}</p>" + "<p>Company: {company}</p>" + "<p>Kids: " + "<tpl for='kids'>" + // interrogate the kids property within the data "<p>{name}</p>" + "</tpl></p>") SafeHtml renderPerson(Person person); } SafeHtml content = tpl.renderPerson(person);
When processing a sub-template, for example while looping through a child array, you can access the parent object's members via the parent object:
interface ParentChildTemplate extends XTemplates { @XTemplate("<p>Name: {name}</p>" + "<p>Kids: " + "<tpl for=\"kids\">" + "<tpl if=\"age > 1\">" + "<p>{name}</p>" + "<p>Dad: {<b>parent</b>.name}</p>" + "</tpl>" + "</tpl></p>") SafeHtml renderParentAndChildren(Person person); } SafeHtml content = tpl.renderParentAndChildren(person);
Conditional Support
The tpl tag and the if operator are used to provide conditional checks for deciding whether or not to render specific parts of the template. Notes:
- If quotes are to be used in the conditionals, they must either be different quotes than were used to define the if, or must be escaped.
- Greater-than (>) symbols must be escaped within conditionals as >
- There is no else operator — if needed, two opposite if statements should be used.
<tpl if="age > 1 && age < 10">Child</tpl> <tpl if="age >= 10 && age < 18">Teenager</tpl> <tpl if="id==\'download\'">...</tpl> <tpl if="needsIcon"><img src="{icon}" class="{iconCls}"/></tpl> // no good: <tpl if="name == "Jack"">Hello</tpl> // encode " if it is part of the condition, e.g. <tpl if="name == "Jack"">Hello</tpl>
Using the sample data above:
interface OlderChildListTemplate extends XTemplates { @XTemplate("<p>Name: {name}</p>" + "<p>Kids: " + "<tpl for=\"kids\">" + // either double quotes (escaped) "<tpl if='age > 1'>" + // or single are allowed "<p>{name}</p>" + // (no need to escape either in an external file) "</tpl>" + "</tpl></p>") SafeHtml renderFamilyOf(Person person); ); SafeHtml content = tpl.renderFamilyOf(person);
Basic Math and Expressions
The following basic math operators may be applied directly on numeric data values: + - * /
To be returned as part of the template, expressions must be contained within
{[ ... ]}
brackets.For example:
interface FutureAgesTemplate extends XTemplates { @XTemplate("<p>Name: {name}</p>" + "<p>Kids: " + "<tpl for=\"kids\">" + "<tpl if=\"age > 1\">" + // <-- Note that the > is encoded "<p>{#}: {name}</p>" + // <-- Auto-number each item "<p>In 5 Years: {[age+5]}</p>" + // <-- Basic math "<p>Dad: {parent.name}</p>" + "</tpl>" + "</tpl></p>") SafeHtml renderFutureChildAges(Person person); ); SafeHtml content = tpl.renderFutureChildAges(person);
-
-
Nested Class Summary
Nested Classes Modifier and Type Interface Description static interface
XTemplates.Formatter<T>
A simple interface to facilitate creation of custom formatters.static interface
XTemplates.FormatterFactories
Collection ofXTemplates.FormatterFactory
instances.static interface
XTemplates.FormatterFactory
Declares that a class may act as a factory to provide formatter instances.static interface
XTemplates.FormatterFactoryMethod
Allows methods to be called on a factory other than 'getFormat'.static interface
XTemplates.TemplateCondition
Defines a single method on an object that should be accessible from within XTemplate conditional statements.static interface
XTemplates.TemplateConditions
Holds a collection ofXTemplates.TemplateCondition
instances, allowing more than one to be declared at a time.static interface
XTemplates.XTemplate
Indicates the string that should be used when generating the template.
-