Wt  3.2.1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Groups Pages
Classes | Public Types | Public Member Functions | Protected Member Functions
Wt::WTemplate Class Reference

A widget that renders an XHTML template. More...

#include <Wt/WTemplate>

Inheritance diagram for Wt::WTemplate:
Inheritance graph
[legend]

List of all members.

Classes

struct  Functions
 A collection of predefined functions. More...

Public Types

typedef boost::function< bool(WTemplate
*t, const std::vector< WString >
&args, std::ostream &result)> 
Function
 A function type.

Public Member Functions

 WTemplate (WContainerWidget *parent=0)
 Creates a template widget.
 WTemplate (const WString &text, WContainerWidget *parent=0)
 Creates a template widget with given template.
const WStringtemplateText () const
 Returns the template.
void setTemplateText (const WString &text, TextFormat textFormat=XHTMLText)
 Sets the template text.
void bindString (const std::string &varName, const WString &value, TextFormat textFormat=XHTMLText)
 Binds a string value to a variable.
void bindInt (const std::string &varName, int value)
 Binds an integer value to a variable.
void bindWidget (const std::string &varName, WWidget *widget)
 Binds a widget to a variable.
void bindEmpty (const std::string &varName)
 Binds an empty string to a variable.
void addFunction (const std::string &name, const Function &function)
 Binds a function.
void setCondition (const std::string &name, bool value)
 Sets a condition.
bool conditionValue (const std::string &name) const
 Returns a condition value.
virtual void resolveString (const std::string &varName, const std::vector< WString > &args, std::ostream &result)
 Resolves the string value for a variable name.
virtual void handleUnresolvedVariable (const std::string &varName, const std::vector< WString > &args, std::ostream &result)
 Handles a variable that could not be resolved.
virtual WWidgetresolveWidget (const std::string &varName)
 Resolves a widget for a variable name.
virtual bool resolveFunction (const std::string &name, const std::vector< WString > &args, std::ostream &result)
 Resolves a function call.
template<typename T >
resolve (const std::string &varName)
 Returns a widget for a variable name.
void clear ()
 Erases all variable bindings.
void setInternalPathEncoding (bool enabled)
 Enables internal path anchors in the XHTML template.
bool hasInternalPathEncoding () const
 Returns whether internal paths are enabled.
virtual void refresh ()
 Refreshes the template.
virtual void renderTemplate (std::ostream &result)
 Renders the template into the given result stream.
- Public Member Functions inherited from Wt::WInteractWidget
 WInteractWidget (WContainerWidget *parent=0)
 Create an InteractWidget with optional parent.
EventSignal< WKeyEvent > & keyWentDown ()
 Event signal emitted when a keyboard key is pushed down.
EventSignal< WKeyEvent > & keyPressed ()
 Event signal emitted when a "character" was entered.
EventSignal< WKeyEvent > & keyWentUp ()
 Event signal emitted when a keyboard key is released.
EventSignalenterPressed ()
 Event signal emitted when enter was pressed.
EventSignalescapePressed ()
 Event signal emitted when escape was pressed.
EventSignal< WMouseEvent > & clicked ()
 Event signal emitted when a mouse key was clicked on this widget.
EventSignal< WMouseEvent > & doubleClicked ()
 Event signal emitted when a mouse key was double clicked on this widget.
EventSignal< WMouseEvent > & mouseWentDown ()
 Event signal emitted when a mouse key was pushed down on this widget.
EventSignal< WMouseEvent > & mouseWentUp ()
 Event signal emitted when a mouse key was released on this widget.
EventSignal< WMouseEvent > & mouseWentOut ()
 Event signal emitted when the mouse went out of this widget.
EventSignal< WMouseEvent > & mouseWentOver ()
 Event signal emitted when the mouse entered this widget.
EventSignal< WMouseEvent > & mouseMoved ()
 Event signal emitted when the mouse moved over this widget.
EventSignal< WMouseEvent > & mouseDragged ()
 Event signal emitted when the mouse is dragged over this widget.
EventSignal< WMouseEvent > & mouseWheel ()
 Event signal emitted when the mouse scroll wheel was used.
EventSignal< WTouchEvent > & touchStarted ()
 Event signal emitted when a finger is placed on the screen.
EventSignal< WTouchEvent > & touchEnded ()
 Event signal emitted when a finger is removed from the screen.
EventSignal< WTouchEvent > & touchMoved ()
 Event signal emitted when a finger, which is already placed on the screen, is moved across the screen.
EventSignal< WGestureEvent > & gestureStarted ()
 Event signal emitted when a gesture is started.
EventSignal< WGestureEvent > & gestureChanged ()
 Event signal emitted when a gesture is changed.
EventSignal< WGestureEvent > & gestureEnded ()
 Event signal emitted when a gesture is ended.
void setDraggable (const std::string &mimeType, WWidget *dragWidget=0, bool isDragWidgetOnly=false, WObject *sourceWidget=0)
 Configure dragging for drag and drop.
virtual void load ()
 Loads content just before the widget is used.
virtual bool isEnabled () const
 Returns whether the widget is enabled.
- Public Member Functions inherited from Wt::WWebWidget
 WWebWidget (WContainerWidget *parent=0)
 Construct a WebWidget with a given parent.
virtual void setPositionScheme (PositionScheme scheme)
 Sets the CSS position scheme.
virtual PositionScheme positionScheme () const
 Returns the CSS position scheme.
virtual void setOffsets (const WLength &offset, WFlags< Side > sides=All)
 Sets CSS offsets for a non-statically positioned widget.
virtual WLength offset (Side s) const
 Returns a CSS offset.
virtual void resize (const WLength &width, const WLength &height)
 Resizes the widget.
virtual WLength width () const
 Returns the width.
virtual WLength height () const
 Returns the height.
virtual void setMinimumSize (const WLength &width, const WLength &height)
 Sets a minimum size.
virtual WLength minimumWidth () const
 Returns the minimum width.
virtual WLength minimumHeight () const
 Returns the minimum height.
virtual void setMaximumSize (const WLength &width, const WLength &height)
 Sets a maximum size.
virtual WLength maximumWidth () const
 Returns the maximum width.
virtual WLength maximumHeight () const
 Returns the maximum height.
virtual void setLineHeight (const WLength &height)
 Sets the CSS line height for contained text.
virtual WLength lineHeight () const
 Returns the CSS line height for contained text.
virtual void setFloatSide (Side s)
 Specifies a CSS float side.
virtual Side floatSide () const
 Returns the CSS float side.
virtual void setClearSides (WFlags< Side > sides)
 Sets the sides that should be cleared of floats.
virtual WFlags< SideclearSides () const
 Returns the sides that should remain empty.
virtual void setMargin (const WLength &margin, WFlags< Side > sides=All)
 Sets CSS margins around the widget.
virtual WLength margin (Side side) const
 Returns a CSS margin set.
virtual void setHiddenKeepsGeometry (bool enabled)
 Sets whether the widget keeps its geometry when hidden.
virtual bool hiddenKeepsGeometry () const
 Returns whether the widget keeps its geometry when hidden.
virtual void setHidden (bool hidden, const WAnimation &animation=WAnimation())
 Hides or shows the widget.
virtual bool isHidden () const
 Returns whether the widget is set hidden.
virtual bool isVisible () const
 Returns whether the widget is visible.
virtual void setDisabled (bool disabled)
 Sets whether the widget is disabled.
virtual bool isDisabled () const
 Returns whether the widget is set disabled.
virtual void setPopup (bool popup)
 Lets the widget overlay over other sibling widgets.
virtual bool isPopup () const
 Returns whether the widget is overlayed.
virtual void setInline (bool isInline)
 Sets whether the widget is displayed inline or as a block.
virtual bool isInline () const
 Returns whether the widget is displayed inline or as block.
virtual void setDecorationStyle (const WCssDecorationStyle &style)
 Sets a CSS decoration style.
virtual WCssDecorationStyledecorationStyle ()
 Returns the decoration style of this widget.
virtual void setStyleClass (const WString &styleClass)
 Sets (one or more) CSS style classes.
virtual WString styleClass () const
 Returns the CSS style class.
virtual void addStyleClass (const WString &styleClass, bool force=false)
 Adds a CSS style class.
virtual void removeStyleClass (const WString &styleClass, bool force=false)
 Removes a CSS style class.
virtual void setVerticalAlignment (AlignmentFlag alignment, const WLength &length=WLength())
 Sets the vertical alignment.
virtual AlignmentFlag verticalAlignment () const
 Returns the vertical alignment.
virtual WLength verticalAlignmentLength () const
 Returns the fixed vertical alignment that was set.
virtual void setToolTip (const WString &text, TextFormat textFormat=PlainText)
 Sets a tooltip.
virtual WString toolTip () const
 Returns the tooltip.
virtual void setAttributeValue (const std::string &name, const WString &value)
 Sets an attribute value.
virtual WString attributeValue (const std::string &name) const
 Returns an attribute value.
virtual void setJavaScriptMember (const std::string &name, const std::string &value)
 Sets a JavaScript member.
virtual std::string javaScriptMember (const std::string &name) const
 Returns the value of a JavaScript member.
virtual void callJavaScriptMember (const std::string &name, const std::string &args)
 Calls a JavaScript member.
virtual bool loaded () const
 Returns whether this widget has been loaded.
virtual void setTabIndex (int index)
 Sets the tab index.
virtual int tabIndex () const
 Returns the tab index.
virtual void setId (const std::string &id)
 Sets the CSS Id.
virtual WWidgetfind (const std::string &name)
 Finds a descendent widget by name.
virtual void setSelectable (bool selectable)
 Sets as selectable.
virtual void doJavaScript (const std::string &javascript)
 Executes the given JavaScript statements when the widget is rendered or updated.
virtual const std::string id () const
 Returns the (unique) identifier for this object.
void setLoadLaterWhenInvisible (bool)
 Change the way the widget is loaded when invisible.
const std::vector< WWidget * > & children () const
 Returns contained widgets.
SignalchildrenChanged ()
 Signal emitted when children have been added or removed.
bool isRendered () const
 Returns whether the widget is rendered.
- Public Member Functions inherited from Wt::WWidget
virtual ~WWidget ()
 Destructor.
WWidgetparent () const
 Returns the parent widget.
void setWidth (const WLength &width)
 Sets the width.
void setHeight (const WLength &height)
 Sets the height.
virtual void positionAt (const WWidget *widget, Orientation orientation=Vertical)
 Positions a widget next to another widget.
std::string jsRef () const
 Returns a JavaScript expression to the corresponding DOM node.
virtual void acceptDrops (const std::string &mimeType, const WString &hoverStyleClass=WString())
 Sets a mime type to be accepted for dropping.
virtual void stopAcceptDrops (const std::string &mimeType)
 Indicates that a mime type is no longer accepted for dropping.
virtual void htmlText (std::ostream &out)
 Streams the (X)HTML representation.
void hide ()
 Hides the widget.
void animateHide (const WAnimation &animation)
 Hides the widget using an animation.
void show ()
 Shows the widget.
void animateShow (const WAnimation &animation)
 Shows the widget using an animation.
void enable ()
 Enables the widget.
void disable ()
 Disable thes widget.
bool layoutSizeAware () const
 Returns whether the widget is layout size aware.
- Public Member Functions inherited from Wt::WObject
 WObject (WObject *parent=0)
 Create a WObject with a given parent object.
virtual ~WObject ()
 Destructor.
void setObjectName (const std::string &name)
 Sets an object name.
virtual std::string objectName () const
 Returns the object name.
void resetLearnedSlots ()
 Resets learned stateless slot implementations.
template<class T >
void resetLearnedSlot (void(T::*method)())
 Resets a learned stateless slot implementation.
template<class T >
WStatelessSlot * implementStateless (void(T::*method)())
 Declares a slot to be stateless and learn client-side behaviour on first invocation.
template<class T >
WStatelessSlot * implementStateless (void(T::*method)(), void(T::*undoMethod)())
 Declares a slot to be stateless and learn client-side behaviour in advance.
template<class T >
WStatelessSlot * implementJavaScript (void(T::*method)(), const std::string &jsCode)
 Provides a JavaScript implementation for a method.
void addChild (WObject *child)
 Adds a child object.

Protected Member Functions

virtual void applyArguments (WWidget *w, const std::vector< WString > &args)
 Applies arguments to a resolved widget.
void format (std::ostream &result, const std::string &s, TextFormat textFormat=PlainText)
 Utility method to safely format an XHTML string.
void format (std::ostream &result, const WString &s, TextFormat textFormat=PlainText)
 Utility method to safely format an XHTML string.
virtual void enableAjax ()
 Progresses to an Ajax-enabled widget.
- Protected Member Functions inherited from Wt::WInteractWidget
virtual void propagateSetEnabled (bool enabled)
 Propagates that a widget was enabled or disabled through children.
- Protected Member Functions inherited from Wt::WWebWidget
virtual void removeChild (WObject *child)
 Removes a child object.
- Protected Member Functions inherited from Wt::WWidget
void setLayoutSizeAware (bool sizeAware)
 Sets the widget to be aware of its size set by a layout manager.
virtual void layoutSizeChanged (int width, int height)
 Virtual method that indicates a size change.
 WWidget (WContainerWidget *parent=0)
 Creates a widget.
virtual void dropEvent (WDropEvent dropEvent)
 Handles a drop event.
virtual int boxPadding (Orientation orientation) const
 Returns the widget's built-in padding.
virtual int boxBorder (Orientation orientation) const
 Returns the widget's built-in border width.
virtual WStatelessSlot * getStateless (Method method)
 On-demand stateless slot implementation.

Detailed Description

A widget that renders an XHTML template.

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 "$${".

There are currently two syntactic constructs defined.

A. Variable placeholders

${var} defines a placeholder for the variable "var", and gets replaced with whatever is bound to that variable:

Optionally, additional arguments can be specified using the following syntax:

${var arg1="A value" arg2='A second value'}

The arguments can thus be simple 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.

Functions are resolved by resolveFunction(), and the default implementation considers functions bound with addFunction(). There are currently two functions that are generally useful:

C. Conditional blocks

${<cond>} starts a conditional block with a condition name "cond", and must be closed by a balanced ${>/cond>}.

Conditions are set using setCondition().

Usage example

WString userName = ...;
WTemplate *t = new WTemplate();
t->setTemplateText("<div> How old are you, ${friend} ? ${age-input} </div>");
t->bindString("friend", userName, PlainText);
t->bindWidget("age-input", ageEdit_ = new WLineEdit());

The template can return a bound widget using resolve(), which already tries to cast the widget to the proper type.

CSS

This widget does not provide styling, and can be styled using inline or external CSS as appropriate.


Member Typedef Documentation

typedef boost::function<bool(WTemplate *t, const std::vector<WString>& args, std::ostream& result)> Wt::WTemplate::Function

A function type.

See also:
addFunction()
Functions::tr(), Functions::id()

Constructor & Destructor Documentation

Wt::WTemplate::WTemplate ( const WString text,
WContainerWidget parent = 0 
)

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 a WText when configured with the Wt::XHTMLText textformat.


Member Function Documentation

void Wt::WTemplate::addFunction ( const std::string &  name,
const Function function 
)

Binds a function.

Functions are useful to automatically resolve placeholders.

The syntax for a function 'fun' applied to a single argument 'bla' is:

${fun:bla}

There are two predefined functions, which can be bound using:

WTemplate *t = ...;
t->addFunction("id", &WTemplate::Functions::id);
t->addFunction("tr", &WTemplate::Functions::tr);
void Wt::WTemplate::applyArguments ( WWidget w,
const std::vector< WString > &  args 
)
protectedvirtual

Applies arguments to a resolved widget.

Currently only a class argument is handled, which adds one or more style classes to the widget w, using WWidget::addStyleClass().

void Wt::WTemplate::bindEmpty ( const std::string &  varName)

Binds an empty string to a variable.

See also:
bindString()
void Wt::WTemplate::bindInt ( const std::string &  varName,
int  value 
)

Binds an integer value to a variable.

See also:
bindString()
void Wt::WTemplate::bindString ( const std::string &  varName,
const WString value,
TextFormat  textFormat = XHTMLText 
)

Binds a string value to a variable.

Each occurrence of the variable within the template will be substituted by its value.

Depending on the textFormat, the value is validated according as for a WText.

See also:
bindWidget(), bindInt()
resolveString()
void Wt::WTemplate::bindWidget ( const std::string &  varName,
WWidget widget 
)

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.

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 0 widget, which will resolve to an empty string.

See also:
bindString()
resolveWidget()
void Wt::WTemplate::clear ( )

Erases all variable bindings.

Removes all strings and deletes all widgets that were previously bound using bindString() and bindWidget().

This also resets all conditions set using setCondition(), but does not remove functions added with addFunction()

bool Wt::WTemplate::conditionValue ( const std::string &  name) const

Returns a condition value.

See also:
setCondition()
void Wt::WTemplate::enableAjax ( )
protectedvirtual

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.

See also:
WApplication::enableAjax()

Reimplemented from Wt::WWebWidget.

void Wt::WTemplate::format ( std::ostream &  result,
const std::string &  s,
TextFormat  textFormat = PlainText 
)
protected

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 specializing resolveString() to avoid security risks.

void Wt::WTemplate::format ( std::ostream &  result,
const WString s,
TextFormat  textFormat = PlainText 
)
protected

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 specializing resolveString() to avoid security risks.

void Wt::WTemplate::handleUnresolvedVariable ( const std::string &  varName,
const std::vector< WString > &  args,
std::ostream &  result 
)
virtual

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. The format() methods may be used for this purpose.
See also:
resolveString()
bool Wt::WTemplate::hasInternalPathEncoding ( ) const

Returns whether internal paths are enabled.

See also:
setInternalPathEncoding()
void Wt::WTemplate::refresh ( )
virtual

Refreshes the template.

This rerenders the template.

Reimplemented from Wt::WWebWidget.

void Wt::WTemplate::renderTemplate ( std::ostream &  result)
virtual

Renders the 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.

template<typename T >
T Wt::WTemplate::resolve ( const std::string &  varName)

Returns a widget for a variable name.

This is a convience method, which calls resolveWidget() and casts the result to type T. You may use this method to fetch widgets that have previously been bound using bindWidget().

bool Wt::WTemplate::resolveFunction ( const std::string &  name,
const std::vector< WString > &  args,
std::ostream &  result 
)
virtual

Resolves a function call.

This resolves a function with name name, and one or more arguments args, and writes the result into the stream result. The method returns whether a function was matched and applied.

The default implementation considers functions that were bound using addFunction().

See also:
addFunction()
void Wt::WTemplate::resolveString ( const std::string &  varName,
const std::vector< WString > &  args,
std::ostream &  result 
)
virtual

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 using resolveWidget(), 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. The format() methods may be used for this purpose.
See also:
renderTemplate()
WWidget * Wt::WTemplate::resolveWidget ( const std::string &  varName)
virtual

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 by clear() (unless bind was called on them as in the example below).

This method is typically used for delayed binding of widgets. Usage example:

{
if (Widget *known = WTemplate::resolveWidget(varName)) {
return known;
} else {
if (varName == "age-input") {
WWidget *w = new WLineEdit(); // widget only created when used
bind(varName, w);
return w;
}
}
}
void Wt::WTemplate::setCondition ( const std::string &  name,
bool  value 
)

Sets a condition.

This enables or disables the inclusion of a conditional block.

The default value of all conditions is false.

void Wt::WTemplate::setInternalPathEncoding ( bool  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.

See also:
WAnchor::setRefInternalPath()
void Wt::WTemplate::setTemplateText ( const WString text,
TextFormat  textFormat = XHTMLText 
)

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 is Wt::XHTMLUnsafeText. This behavior is similar to a WText when configured with the Wt::XHTMLText textformat.

Changing the template text does not clear() bound widgets or values.

See also:
clear()
const WString& Wt::WTemplate::templateText ( ) const

Returns the template.

See also:
setTemplateText()

Generated on Sun May 27 2012 for the C++ Web Toolkit (Wt) by doxygen 1.8.1