Class WTemplate
- Direct Known Subclasses:
LostPasswordWidget
,ResendEmailVerificationWidget
,WNavigationBar
,WTemplateFormView
The XHTML template may contain references to variables which replaced by strings are widgets.
Since the template text may be supplied by a WString
, you can conveniently store the
string in a message resource bundle, and make it localized by using WString#tr()
.
Placeholders (for variables and functions) are delimited by: ${...}
. To use a
literal "${"
, use "$${"
. Place holder names can
contain '_', '-', '.' and alfanumeric characters.
Usage example:
WString userName = ...;
WTemplate t = new WTemplate();
t.setTemplateText("<div> How old are you, ${friend} ? ${age-input} </div>");
t.bindString("friend", userName, TextFormat::Plain);
t.bindWidget("age-input", ageEdit_ = new WLineEdit());
There are currently three syntactic constructs defined: variable place holders, functions and conditional blocks.
A. Variable placeholders
${var}
defines a placeholder for the variable "var", and gets replaced
with whatever is bound to that variable:
- a widget, using
bindWidget()
- a string value, using
bindString()
orbindInt()
- or in general, the result of
resolveString()
andresolveWidget()
methods.
Optionally, additional arguments can be specified using the following syntax:
${var arg1="A value" arg2='A second value'}
The arguments can thus be simple strings or quoted strings (single or double quoted). These
arguments are applied to a resolved widget in applyArguments()
and currently supports only style classes.
You can bind widgets and values to variables using bindWidget()
, bindString()
or bindInt()
or by reimplementing the resolveString()
and resolveWidget()
methods.
Note: The use of XML comments (<!-- ... -.
) around variables that
are bound to widgets will result in bad behaviour since the template parser is ignorant about
these comments and the corresponding widgets will believe that they are rendered but aren't
actually.
B. Functions
${fun:arg}
defines a placeholder for applying a function "fun" to an
argument "arg".
Optionally, additional arguments can be specified as with a variable placeholder.
WTemplate.Functions
are resolved by resolveFunction()
, and the default implementation considers functions bound with
addFunction()
. There are
currently three functions that are generally useful:
- : resolves a localized strings, this is convenient to create a language neutral template, which contains translated strings Functions::id : resolves the id of a bound widget, this is convenient to bind <label> elements to a form widget using its for attribute.
- : recursively renders another string as macro block optional arguments substituted before processing template substitution. For example, the following template uses the "tr" function to translate the age-label using the "age-label" internationalized key. WTemplate t = new WTemplate(); t.setTemplateText("<div> ${tr:age-label} ${age-input} </div>"); t.addFunction("tr", WTemplate.Functions.tr); t.bindWidget("age-input", ageEdit = new WLineEdit()); C. Conditional blocks
${<cond>}
starts a conditional block with a condition name
"cond", and must be closed by a balanced ${</cond>}
.
For example:
WTemplate t = new WTemplate();
t.setTemplateText("<div> ${<if-register>} Register ... ${</if-register>}</div>");
t.setCondition("if-register", true);
Conditions are set using setCondition()
.
CSS
This widget does not provide styling, and can be styled using inline or external CSS as appropriate.
-
Nested Class Summary
Modifier and TypeClassDescriptionstatic interface
A function interface type.static class
A collection of predefined functions.Nested classes/interfaces inherited from class eu.webtoolkit.jwt.WObject
WObject.FormData
-
Field Summary
Fields inherited from class eu.webtoolkit.jwt.WInteractWidget
dragTouchEndSlot_, dragTouchSlot_
-
Constructor Summary
ConstructorDescriptionCreates a template widget.WTemplate
(WContainerWidget parentContainer) Creates a template widget.WTemplate
(CharSequence text) Creates a template widget with given template.WTemplate
(CharSequence text, WContainerWidget parentContainer) Creates a template widget with given template. -
Method Summary
Modifier and TypeMethodDescriptionvoid
addFunction
(String name, WTemplate.Function function) Binds a function.protected void
applyArguments
(WWidget w, List<WString> args) Applies arguments to a resolved widget.void
Binds an empty string to a variable.void
Binds an integer value to a variable.final void
bindString
(String varName, CharSequence value) Binds a string value to a variable.void
bindString
(String varName, CharSequence value, TextFormat textFormat) Binds a string value to a variable.bindWidget
(String varName, WWidget widget) Binds a widget to a variable.void
clear()
Erases all variable bindings.boolean
conditionValue
(String name) Returns a condition value.protected void
Progresses to an Ajax-enabled widget.protected final void
format
(Writer result, CharSequence s) Utility method to safely format an XHTML string.protected void
format
(Writer result, CharSequence s, TextFormat textFormat) Utility method to safely format an XHTML string.protected final void
Utility method to safely format an XHTML string.protected void
format
(Writer result, String s, TextFormat textFormat) Utility method to safely format an XHTML string.Returns the set of conditions set to true.Renders the errors during renderring.Returns the template.Returns how the varName is reflected on a bound widget.void
handleUnresolvedVariable
(String varName, List<WString> args, Writer result) Handles a variable that could not be resolved.boolean
Returns whether internal paths are enabled.boolean
Returns whether internal path encoding is done on the template text.protected void
iterateChildren
(HandleWidgetMethod method) void
refresh()
Refresh the widget.void
remove()
Destructor.removeWidget
(WWidget widget) Unbinds a widget by widget pointer.removeWidget
(String varName) Unbinds a widget by variable name.void
renderTemplate
(Writer result) Renders the template into the given result stream.boolean
renderTemplateText
(Writer result, CharSequence templateText) Renders a template into the given result stream.protected void
reset()
Notifies the template that it has changed and must be rerendered.boolean
resolveFunction
(String name, List<WString> args, Writer result) Resolves a function call.void
resolveString
(String varName, List<WString> args, Writer result) Resolves the string value for a variable name.resolveStringValue
(String varName) Resolves a string that was bound to a variable name.resolveWidget
(String varName) Resolves a widget for a variable name.void
setCondition
(String name, boolean value) Sets a condition.void
setEncodeTemplateText
(boolean on) Configures when internal path encoding is done.void
setInternalPathEncoding
(boolean enabled) Enables internal path anchors in the XHTML template.final void
setTemplateText
(CharSequence text) Sets the template text.void
setTemplateText
(CharSequence text, TextFormat textFormat) Sets the template text.void
Sets how the varName should be reflected on bound widgets.Methods inherited from class eu.webtoolkit.jwt.WInteractWidget
clicked, doubleClicked, enterPressed, escapePressed, gestureChanged, gestureEnded, gestureStarted, getMouseOverDelay, isEnabled, keyPressed, keyWentDown, keyWentUp, load, mouseDragged, mouseMoved, mouseWentDown, mouseWentOut, mouseWentOver, mouseWentUp, mouseWheel, propagateSetEnabled, setDraggable, setDraggable, setDraggable, setDraggable, setMouseOverDelay, setPopup, touchEnded, touchMoved, touchStarted, unsetDraggable
Methods inherited from class eu.webtoolkit.jwt.WWebWidget
addStyleClass, beingDeleted, blurred, callJavaScriptMember, childrenChanged, createDomElement, doJavaScript, escapeText, escapeText, escapeText, escapeText, find, findById, focussed, getAttributeValue, getBaseZIndex, getChildren, getClearSides, getDecorationStyle, getDomChanges, getFloatSide, getHeight, getHtmlTagName, getId, getJavaScriptMember, getLineHeight, getMargin, getMaximumHeight, getMaximumWidth, getMinimumHeight, getMinimumWidth, getOffset, getPositionScheme, getScrollVisibilityMargin, getStyleClass, getTabIndex, getToolTip, getVerticalAlignment, getVerticalAlignmentLength, getWidth, hasFocus, hasStyleClass, isCanReceiveFocus, isDisabled, isHidden, isHiddenKeepsGeometry, isInline, isLoaded, isPopup, isRendered, isScrollVisibilityEnabled, isScrollVisible, isSetFirstFocus, isThemeStyleEnabled, isVisible, jsStringLiteral, jsStringLiteral, manageWidget, parentResized, parentResized, propagateSetVisible, removeScript, removeStyleClass, render, resize, scrollVisibilityChanged, setAttributeValue, setBaseZIndex, setCanReceiveFocus, setClearSides, setDecorationStyle, setDeferredToolTip, setDisabled, setFlexBox, setFloatSide, setFocus, setHidden, setHiddenKeepsGeometry, setHtmlTagName, setId, setInline, setJavaScriptMember, setLineHeight, setLoadLaterWhenInvisible, setMargin, setMaximumSize, setMinimumSize, setObjectName, setOffsets, setParentWidget, setPositionScheme, setScrollVisibilityEnabled, setScrollVisibilityMargin, setSelectable, setStyleClass, setTabIndex, setThemeStyleEnabled, setToolTip, setVerticalAlignment, unescapeText, updateSignalConnection, voidEventSignal, widgetAdded, widgetRemoved
Methods inherited from class eu.webtoolkit.jwt.WWidget
acceptDrops, acceptDrops, addCssRule, addCssRule, addJSignal, addStyleClass, animateHide, animateShow, boxBorder, boxPadding, createJavaScript, disable, dropEvent, enable, getDropTouch, getJsRef, getParent, hide, htmlText, isExposed, isGlobalWidget, isLayoutSizeAware, layoutSizeChanged, needsRerender, positionAt, positionAt, removeFromParent, removeStyleClass, render, resize, scheduleRender, scheduleRender, scheduleRender, setClearSides, setDeferredToolTip, setFocus, setHeight, setHidden, setLayoutSizeAware, setMargin, setMargin, setMargin, setMargin, setMargin, setOffsets, setOffsets, setOffsets, setOffsets, setOffsets, setToolTip, setVerticalAlignment, setWidth, show, stopAcceptDrops, toggleStyleClass, toggleStyleClass, tr
Methods inherited from class eu.webtoolkit.jwt.WObject
getObjectName, setFormData
-
Constructor Details
-
WTemplate
Creates a template widget. -
WTemplate
public WTemplate()Creates a template widget. -
WTemplate
Creates a template widget with given template.The
templateText
must be proper XHTML, and this is checked unless the XHTML is resolved from a message resource bundle. This behavior is similar to aWText
when configured with theTextFormat.XHTML
textformat. -
WTemplate
Creates a template widget with given template.
-
-
Method Details
-
remove
public void remove()Description copied from class:WWidget
Destructor.Deletes a widget and all contained contents.
- Overrides:
remove
in classWInteractWidget
- See Also:
-
getTemplateText
Returns the template. -
setTemplateText
Sets the template text.The
text
must be proper XHTML, and this is checked unless the XHTML is resolved from a message resource bundle or TextFormat isTextFormat.UnsafeXHTML
. This behavior is similar to aWText
when configured with theTextFormat.XHTML
textformat.Changing the template text does not
clear()
bound widgets or values.- See Also:
-
setTemplateText
Sets the template text. -
setWidgetIdMode
Sets how the varName should be reflected on bound widgets.To easily identify a widget in the browser, it may be convenient to reflect the varName, either through the object name (recommended) or the widget's ID.
The default value is
TemplateWidgetIdMode.None
which does not reflect the varName on the bound widget. -
getWidgetIdMode
Returns how the varName is reflected on a bound widget. -
bindString
Binds a string value to a variable.Each occurrence of the variable within the template will be substituted by its value.
Note: Depending on the
textFormat
, thevalue
is validated according as for aWText
. The default (TextFormat.XHTML
) filters "active" content, to avoid XSS-based security risks. -
bindString
Binds a string value to a variable. -
bindInt
Binds an integer value to a variable. -
bindWidget
Binds a widget to a variable.The corresponding variable reference within the template will be replaced with the widget (rendered as XHTML). Since a single widget may be instantiated only once in a template, the variable
varName
may occur at most once in the template, and thewidget
must not yet be bound to another variable.The widget is reparented to the
WTemplate
, so that it is deleted when theWTemplate
is deleted.If a widget was already bound to the variable, it is deleted first. If previously a string or other value was bound to the variable, it is removed.
You may also pass a
null
widget
, which will resolve to an empty string. -
removeWidget
Unbinds a widget by variable name.This removes a previously bound widget and unbinds the corresponding variable, effectively undoing the effect of
bindWidget()
.If this template does not contain a widget for the given
varName
,null
is returned. -
removeWidget
Unbinds a widget by widget pointer.This removes a previously bound widget and unbinds the corresponding variable, effectively undoing the effect of
bindWidget()
.If this template does not contain the given widget,
null
is returned.- Overrides:
removeWidget
in classWWidget
-
bindEmpty
Binds an empty string to a variable.If a widget was bound to the variable, it is deleted first.
-
addFunction
Binds a function.WTemplate.Functions
are useful to automatically resolve placeholders.The syntax for a function 'fun' applied to a single argument 'bla' is:
${fun:bla}
There are three predefined functions, which can be bound using:
WTemplate t = ...; t.addFunction("id", WTemplate.Functions.id); t.addFunction("tr", WTemplate.Functions.tr); t.addFunction("block", WTemplate.Functions.block);
-
setCondition
Sets a condition.This enables or disables the inclusion of a conditional block.
The default value of all conditions is
false
. -
conditionValue
Returns a condition value.- See Also:
-
getConditionsSet
Returns the set of conditions set to true. -
resolveString
Resolves the string value for a variable name.This is the main method used to resolve variables in the template text, during rendering.
The default implementation considers first whether a string was bound using
bindString()
. If so, that string is returned. If not, it will attempt to resolve a widget with that variable name usingresolveWidget()
, and render it as XHTML. If that fails too,handleUnresolvedVariable()
is called, passing the initial arguments.You may want to reimplement this method to provide on-demand loading of strings for your template.
The result stream expects a UTF-8 encoded string value.
Warning: When specializing this class, you need to make sure that you append proper XHTML to the
result
, without unsafe active contents. Theformat()
methods may be used for this purpose.- Throws:
IOException
- See Also:
-
handleUnresolvedVariable
public void handleUnresolvedVariable(String varName, List<WString> args, Writer result) throws IOException Handles a variable that could not be resolved.This method is called from
resolveString()
for variables that could not be resolved.The default implementation implementation writes "??" + varName + "??" to the result stream.
The result stream expects a UTF-8 encoded string value.
Warning: When specializing this class, you need to make sure that you append proper XHTML to the
result
, without unsafe active contents. Theformat()
methods may be used for this purpose.- Throws:
IOException
- See Also:
-
resolveWidget
Resolves a widget for a variable name.The default implementation returns a widget that was bound using
bindWidget()
.You may want to reimplement this method to create widgets on-demand. All widgets that are returned by this method are reparented to the
WTemplate
, so they will be deleted when the template is destroyed, but they are not deleted byclear()
(unless bind was called on them as in the example below).This method is typically used for delayed binding of widgets. Usage example:
if (WWidget known = super.resolveWidget(varName)) { return known; } else { if (varName == "age-input") { WWidget w = new WLineEdit(); // widget only created when used bindWidget(varName, w); return w; } }
-
resolveStringValue
Resolves a string that was bound to a variable name.Returns the string that was bound to the variable with
bindString()
.This method is not to be confused with
resolveString()
which resolves any variable to a string (both strings and widgets alike). -
getWidgets
-
varName
-
resolveFunction
Resolves a function call.This resolves a function with name
name
, and one or more argumentsargs
, and writes the result into the streamresult
. The method returns whether a function was matched and applied.The default implementation considers functions that were bound using
addFunction()
.- Throws:
IOException
- See Also:
-
clear
public void clear()Erases all variable bindings.Removes all strings and deletes all widgets that were previously bound using
bindString()
andbindWidget()
.This also resets all conditions set using
setCondition()
, but does not remove functions added withaddFunction()
-
setInternalPathEncoding
public void setInternalPathEncoding(boolean enabled) Enables internal path anchors in the XHTML template.Anchors to internal paths are represented differently depending on the session implementation (plain HTML, Ajax or HTML5 history). By enabling this option, anchors which reference an internal path (by referring a URL of the form
href="#/..."
), are re-encoded to link to the internal path.The default value is
false
. -
hasInternalPathEncoding
public boolean hasInternalPathEncoding()Returns whether internal paths are enabled.- See Also:
-
setEncodeTemplateText
public void setEncodeTemplateText(boolean on) Configures when internal path encoding is done.By default, the internal path encoding (if enabled) is done on the template text before placeholders are being resolved. In some rare situations, you may want to postpone the internal path encoding until after placeholders have been resolved, e.g. if a placeholder was used to provide the string for an anchor href.
The default value is
true
-
isEncodeTemplateText
public boolean isEncodeTemplateText()Returns whether internal path encoding is done on the template text.- See Also:
-
refresh
public void refresh()Description copied from class:WWidget
Refresh the widget.The refresh method is invoked when the locale is changed using
WApplication#setLocale()
or when the user hit the refresh button.The widget must actualize its contents in response.
Note: This does not rerender the widget! Calling
refresh()
usually does not have any effect (unless you've reimplementedrefresh()
to attach to it an effect).- Overrides:
refresh
in classWWebWidget
-
renderTemplate
Renders the template into the given result stream.The default implementation will call
renderTemplateText()
with thegetTemplateText()
.- Throws:
IOException
-
renderTemplateText
Renders a template into the given result stream.The default implementation will parse the template, and resolve variables by calling
resolveString()
.You may want to reimplement this method to manage resources that are needed to load content on-demand (e.g. database objects), or support a custom template language.
Return: true if rendered successfully. @see WTemplate#getErrorText()
- Throws:
IOException
-
getErrorText
Renders the errors during renderring. -
applyArguments
Applies arguments to a resolved widget.Currently only a
class
argument is handled, which adds one or more style classes to the widgetw
, usingWWidget#addStyleClass()
. -
iterateChildren
- Overrides:
iterateChildren
in classWWebWidget
-
format
Utility method to safely format an XHTML string.The string is formatted according to the indicated
textFormat
. It is recommended to use this method when specializingresolveString()
to avoid security risks.- Throws:
IOException
-
format
Utility method to safely format an XHTML string.- Throws:
IOException
-
format
Utility method to safely format an XHTML string.The string is formatted according to the indicated
textFormat
. It is recommended to use this method when specializingresolveString()
to avoid security risks.- Throws:
IOException
-
format
Utility method to safely format an XHTML string.- Throws:
IOException
-
enableAjax
protected void enableAjax()Description copied from class:WWidget
Progresses to an Ajax-enabled widget.This method is called when the progressive bootstrap method is used, and support for AJAX has been detected. The default behavior will upgrade the widget's event handling to use AJAX instead of full page reloads, and propagate the call to its children.
You may want to reimplement this method if you want to make changes to widget when AJAX is enabled. You should always call the base implementation.
- Overrides:
enableAjax
in classWWebWidget
- See Also:
-
reset
protected void reset()Notifies the template that it has changed and must be rerendered.If you update a
WTemplate
with e.g bindWidget or setCondition, or change the template text, the template will automatically be rerendered.However, if you create a subclass of
WTemplate
and override resolveString or resolveWidget, you will have to notify theWTemplate
if it has changed with a call toreset()
.
-