Wt: Wt::WTemplate Class Reference

Wt 4.10.4

Loading...
Searching...
No Matches
Classes | Public Types | Public Member Functions | Protected Member Functions | List of all members
Wt::WTemplate Class Reference

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

`#include <Wt/WTemplate.h>`

Inheritance diagram for Wt::WTemplate:
[legend]

## Classes
struct | Functions
| A collection of predefined functions. More...

## Public Types
typedef TemplateWidgetIdMode | WidgetIdMode
| Typedef for enum Wt::TemplateWidgetIdMode.
typedef std::function< bool(WTemplate *t, const std::vector< WString > &args, std::ostream &result)> | Function
| A function type.
Public Types inherited from Wt::WObject
typedef void(WObject::*) | Method()
| Typedef for a WObject method without arguments.

## Public Member Functions
| WTemplate ()
| Creates a template widget.
| WTemplate (const WString &text)
| Creates a template widget with given template.
virtual WString | templateText () const
| Returns the template.
void | setTemplateText (const WString &text, TextFormat textFormat=TextFormat::XHTML)
| Sets the template text.
void | setWidgetIdMode (TemplateWidgetIdMode mode)
| Sets how the varName should be reflected on bound widgets.
TemplateWidgetIdMode | widgetIdMode () const
| Returns how the varName is reflected on a bound widget.
virtual void | bindString (const std::string &varName, const WString &value, TextFormat textFormat=TextFormat::XHTML)
| Binds a string value to a variable.
void | bindInt (const std::string &varName, int value)
| Binds an integer value to a variable.
virtual void | bindWidget (const std::string &varName, std::unique_ptr< WWidget > widget)
| Binds a widget to a variable.
template<typename Widget >
Widget * | bindWidget (const std::string &varName, std::unique_ptr< Widget > widget)
| Binds a widget to a variable, returning a raw pointer.
template<typename Widget , typename ... Args>
Widget * | bindNew (const std::string &varName, Args &&...args)
| Creates a new widget with the given arguments, and binds it, returning a raw pointer.
std::unique_ptr< WWidget > | removeWidget (const std::string &varName)
| Unbinds a widget by variable name.
virtual std::unique_ptr< WWidget > | removeWidget (WWidget *widget) override
| Unbinds a widget by widget pointer.
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.
virtual bool | conditionValue (const std::string &name) const
| Returns a condition value.
std::set< std::string > | conditionsSet ()
| Returns the set of conditions set to true.
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 WWidget * | resolveWidget (const std::string &varName)
| Resolves a widget for a variable name.
virtual const WString & | resolveStringValue (const std::string &varName)
| Resolves a string that was bound to 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 >
T | resolve (const std::string &varName)
| Returns a widget for a variable name.
virtual 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.
void | setEncodeTemplateText (bool on)
| Configures when internal path encoding is done.
bool | encodeTemplateText () const
| Returns whether internal path encoding is done on the template text.
virtual void | refresh () override
| Refresh the widget.
virtual void | renderTemplate (std::ostream &result)
| Renders the template into the given result stream.
bool | renderTemplateText (std::ostream &result, const WString &templateText)
| Renders a template into the given result stream.
std::string | getErrorText ()
| Renders the errors during renderring.
template<typename Widget >
std::unique_ptr< Widget > | removeWidget (Widget *widget)
| Removes a child widget.
Public Member Functions inherited from Wt::WInteractWidget
| WInteractWidget ()
| Create an InteractWidget.
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.
EventSignal & | enterPressed ()
| Event signal emitted when enter was pressed.
EventSignal & | escapePressed ()
| Event signal emitted when escape was pressed.
EventSignal< WMouseEvent > & | clicked ()
| Event signal emitted when the primary mouse button was clicked on this widget.
EventSignal< WMouseEvent > & | doubleClicked ()
| Event signal emitted when the primary mouse button was double clicked on this widget.
EventSignal< WMouseEvent > & | mouseWentDown ()
| Event signal emitted when a mouse button was pushed down on this widget.
EventSignal< WMouseEvent > & | mouseWentUp ()
| Event signal emitted when a mouse button 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=nullptr, bool isDragWidgetOnly=false, WObject *sourceWidget=nullptr)
| Configure dragging for drag and drop.
void | unsetDraggable ()
| Disable drag & drop for this widget.
void | setMouseOverDelay (int delay)
| Sets a delay for the mouse over event.
int | mouseOverDelay () const
| Returns the mouse over signal delay.
virtual void | setPopup (bool popup) override
| Lets the widget overlay over other sibling widgets.
virtual void | load () override
| Loads content just before the widget is used.
virtual bool | isEnabled () const override
| Returns whether the widget is enabled.
Public Member Functions inherited from Wt::WWebWidget
| WWebWidget ()
| Construct a WebWidget.
virtual std::vector< WWidget * > | children () const override
| Returns child widgets.
Signal & | childrenChanged ()
| Signal emitted when children have been added or removed.
virtual void | setPositionScheme (PositionScheme scheme) override
| Sets the CSS position scheme.
virtual PositionScheme | positionScheme () const override
| Returns the CSS position scheme.
virtual void | setOffsets (const WLength &offset, WFlags< Side > sides=AllSides) override
| Sets CSS offsets for a non-statically positioned widget.
virtual WLength | offset (Side s) const override
| Returns a CSS offset.
virtual void | resize (const WLength &width, const WLength &height) override
| Resizes the widget.
virtual WLength | width () const override
| Returns the width.
virtual WLength | height () const override
| Returns the height.
virtual void | setMinimumSize (const WLength &width, const WLength &height) override
| Sets a minimum size.
virtual WLength | minimumWidth () const override
| Returns the minimum width.
virtual WLength | minimumHeight () const override
| Returns the minimum height.
virtual void | setMaximumSize (const WLength &width, const WLength &height) override
| Sets a maximum size.
virtual WLength | maximumWidth () const override
| Returns the maximum width.
virtual WLength | maximumHeight () const override
| Returns the maximum height.
virtual void | setLineHeight (const WLength &height) override
| Sets the CSS line height for contained text.
virtual WLength | lineHeight () const override
| Returns the CSS line height for contained text.
virtual void | setFloatSide (Side s) override
| Specifies a CSS float side.
virtual Side | floatSide () const override
| Returns the CSS float side.
virtual void | setClearSides (WFlags< Side > sides) override
| Sets the sides that should be cleared of floats.
virtual WFlags< Side > | clearSides () const override
| Returns the sides that should remain empty.
virtual void | setMargin (const WLength &margin, WFlags< Side > sides=AllSides) override
| Sets CSS margins around the widget.
virtual WLength | margin (Side side) const override
| Returns a CSS margin set.
virtual void | setHiddenKeepsGeometry (bool enabled) override
| Sets whether the widget keeps its geometry when hidden.
virtual bool | hiddenKeepsGeometry () const override
| Returns whether the widget keeps its geometry when hidden.
virtual void | setHidden (bool hidden, const WAnimation &animation=WAnimation()) override
| Hides or shows the widget.
virtual bool | isHidden () const override
| Returns whether the widget is set hidden.
virtual bool | isVisible () const override
| Returns whether the widget is visible.
virtual void | setDisabled (bool disabled) override
| Sets whether the widget is disabled.
virtual bool | isDisabled () const override
| Returns whether the widget is set disabled.
virtual bool | isPopup () const override
| Returns whether the widget is overlayed.
virtual void | setInline (bool isInline) override
| Sets whether the widget is displayed inline or as a block.
virtual bool | isInline () const override
| Returns whether the widget is displayed inline or as block.
virtual void | setDecorationStyle (const WCssDecorationStyle &style) override
| Sets a CSS decoration style.
virtual WCssDecorationStyle & | decorationStyle () override
| Returns the decoration style of this widget.
virtual void | setStyleClass (const WString &styleClass) override
| Sets (one or more) CSS style classes.
virtual WString | styleClass () const override
| Returns the CSS style class.
virtual void | addStyleClass (const WString &styleClass, bool force=false) override
| Adds a CSS style class.
virtual void | removeStyleClass (const WString &styleClass, bool force=false) override
| Removes a CSS style class.
virtual bool | hasStyleClass (const WString &styleClass) const override
| Returns whether the widget has a style class.
virtual void | setVerticalAlignment (AlignmentFlag alignment, const WLength &length=WLength()) override
| Sets the vertical alignment.
virtual AlignmentFlag | verticalAlignment () const override
| Returns the vertical alignment.
virtual WLength | verticalAlignmentLength () const override
| Returns the fixed vertical alignment that was set.
virtual void | setToolTip (const WString &text, TextFormat textFormat=TextFormat::Plain) override
| Sets a tooltip.
virtual void | setDeferredToolTip (bool enable, TextFormat textFormat=TextFormat::Plain) override
| Enable deferred tooltip.
virtual WString | toolTip () const override
| Returns the tooltip.
virtual void | setAttributeValue (const std::string &name, const WString &value) override
| Sets an attribute value.
virtual WString | attributeValue (const std::string &name) const override
| Returns an attribute value.
virtual void | setJavaScriptMember (const std::string &name, const std::string &value) override
| Sets a JavaScript member.
virtual std::string | javaScriptMember (const std::string &name) const override
| Returns the value of a JavaScript member.
virtual void | callJavaScriptMember (const std::string &name, const std::string &args) override
| Calls a JavaScript member.
virtual bool | loaded () const override
| Returns whether this widget has been loaded.
virtual void | setId (const std::string &id) override
| Sets the CSS Id.
virtual WWidget * | find (const std::string &name) override
| Finds a descendent widget by name.
virtual WWidget * | findById (const std::string &id) override
| Finds a descendent widget by id.
virtual void | setSelectable (bool selectable) override
| Sets as selectable.
virtual void | doJavaScript (const std::string &javascript) override
| Executes the given JavaScript statements when the widget is rendered or updated.
virtual const std::string | id () const override
| Returns the (unique) identifier for this object.
void | setLoadLaterWhenInvisible (bool)
| Change the way the widget is loaded when invisible.
std::string | htmlTagName () const
| returns the current html tag name
void | setHtmlTagName (const std::string &tag)
| set the custom HTML tag name
virtual void | setCanReceiveFocus (bool enabled) override
| Sets whether the widget can receive focus.
virtual bool | canReceiveFocus () const override
| Returns whether the widget can receive focus.
virtual bool | setFirstFocus () override
| Set focus on the widget's first descendant.
virtual void | setFocus (bool focus) override
| Sets focus.
virtual bool | hasFocus () const override
| Returns whether the widget currently has the focus.
virtual void | setTabIndex (int index) override
| Sets the tab index.
virtual int | tabIndex () const override
| Returns the tab index.
EventSignal & | blurred ()
| Signal emitted when the widget lost focus.
EventSignal & | focussed ()
| Signal emitted when the widget recieved focus.
virtual bool | scrollVisibilityEnabled () const final override
| Returns whether scroll visibility detection is enabled for this widget.
virtual void | setScrollVisibilityEnabled (bool enabled) final override
| Sets whether scroll visibility detection is enabled for this widget.
virtual int | scrollVisibilityMargin () const final override
| Returns the margin around the viewport within which the widget is considered visible.
virtual void | setScrollVisibilityMargin (int margin) final override
| Sets the margin around the viewport within which the widget is considered visible.
virtual Signal< bool > & | scrollVisibilityChanged () final override
| Signal triggered when the scroll visibility of this widget changes.
virtual bool | isScrollVisible () const final override
| Returns whether this widget is currently considered scroll visible.
virtual void | setThemeStyleEnabled (bool enabled) final override
| Sets whether theme styling for a widget is enabled or disabled.
virtual bool | isThemeStyleEnabled () const final override
| Returns whether this widget is currently styled by the chosen theme.
virtual void | setObjectName (const std::string &name) override
| Sets an object name.
void | setFocus ()
| Sets focus.
Public Member Functions inherited from Wt::WWidget
virtual | ~WWidget ()
| Destructor.
WWidget * | parent () const
| Returns the parent widget.
template<typename Widget >
std::unique_ptr< Widget > | removeWidget (Widget *widget)
| Removes a child widget.
std::unique_ptr< WWidget > | removeFromParent ()
| Removes the widget from its parent.
void | setWidth (const WLength &width)
| Sets the width.
void | setHeight (const WLength &height)
| Sets the height.
virtual void | positionAt (const WWidget *widget, Orientation orientation=Orientation::Vertical)
| Positions a widget next to another widget.
virtual void | toggleStyleClass (const WString &styleClass, bool add, bool force=false)
| Toggles a CSS style class.
std::string | jsRef () const
| Returns a JavaScript expression to the corresponding DOM node.
void | setFocus ()
| Sets focus.
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.
bool | isRendered () const
| Returns whether the widget is rendered.
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
void | addChild (std::unique_ptr< WObject > child)
| Add a child WObject whose lifetime is determined by this WObject.
template<typename Child >
Child * | addChild (std::unique_ptr< Child > child)
| Add a child WObject, returning a raw pointer.
std::unique_ptr< WObject > | removeChild (WObject *child)
| Remove a child WObject, so its lifetime is no longer determined by this WObject.
template<typename Child >
std::unique_ptr< Child > | removeChild (Child *child)
| Remove a child WObject, so its lifetime is no longer determined by this WObject.
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.
void | isNotStateless ()
| Marks the current function as not stateless.
template<class T >
WStatelessSlot * | implementJavaScript (void(T::*method)(), const std::string &jsCode)
| Provides a JavaScript implementation for a method.
Public Member Functions inherited from Wt::Core::observable
| observable () noexcept
| Default constructor.
virtual | ~observable ()
| Destructor.
template<typename... Args, typename C >
auto | bindSafe (void(C::*method)(Args...)) noexcept
| Protects a method call against object destruction.
template<typename... Args, typename C >
auto | bindSafe (void(C::*method)(Args...) const) const noexcept
| Protects a const method call against object destruction.
template<typename Function >
auto | bindSafe (const Function &function) noexcept
| Protects a function against object destruction.

## 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=TextFormat::Plain)
| Utility method to safely format an XHTML string.
void | format (std::ostream &result, const WString &s, TextFormat textFormat=TextFormat::Plain)
| Utility method to safely format an XHTML string.
virtual void | enableAjax () override
| Progresses to an Ajax-enabled widget.
void | reset ()
| Notifies the template that it has changed and must be rerendered.
Protected Member Functions inherited from Wt::WInteractWidget
virtual void | propagateSetEnabled (bool enabled) override
| Propagates that a widget was enabled or disabled through children.
Protected Member Functions inherited from Wt::WWebWidget
virtual WStatelessSlot * | getStateless (Method method) override
| On-demand stateless slot implementation.
virtual void | render (WFlags< RenderFlag > flags) override
| Renders the widget.
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 ()
| 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.
void | scheduleRender (WFlags< RepaintFlag > flags=None)
| Schedules rerendering of the widget.
Protected Member Functions inherited from Wt::WObject

## Additional Inherited Members
Static Public Member Functions inherited from Wt::WWebWidget
static std::string | jsStringLiteral (const std::string &v, char delimiter='\'')
| Turn a CharEncoding::UTF8 encoded string into a JavaScript string literal.
Static Public Member Functions inherited from Wt::WWidget
static WString | tr (const char *key)
| Short hand for WString::tr()
Static Public Member Functions inherited from Wt::WObject
Static Public Attributes inherited from Wt::WWidget
Protected Types inherited from Wt::WWebWidget
Protected Types inherited from Wt::WWidget
Protected Attributes inherited from Wt::WInteractWidget
Static Protected Attributes inherited from Wt::WInteractWidget
Static Protected Attributes inherited from Wt::WWidget

## 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 `"$${"`. Place holder names can contain '_', '-', '.' and alfanumeric characters.

Usage example:

WString userName = ...;
auto t = std::make_unique<WTemplate>();
t->setTemplateText("<div> How old are you, ${friend} ? ${age-input} </div>");
t->bindString("friend", userName, TextFormat::Plain);
ageEdit_ = t->bindWidget("age-input", std::make_unique<WLineEdit>());
Wt::WString
A value class which describes a locale-aware unicode string.
Definition WString.h:74
Wt::TextFormat::Plain
@ Plain
Format text as plain text.

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() or bindInt()
- or in general, the result of resolveString() and resolveWidget() 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.

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. auto t = std::make_unique<WTemplate>(); t->addFunction("tr", &WTemplate::Functions::tr); t->setTemplateText("<div> ${tr:age-label} ${age-input} </div>"); ageEdit_ = t->bindWidget("age-input", std::make_unique<WLineEdit>()); C. Conditional blocks

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

For example:

auto t = std::make_unique<WTemplate>();
t->setTemplateText("<div> ${<if-register>} Register ... ${</if-register>}</div>");
t->setCondition("if-register", true);

Conditions are set using setCondition().

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

## ◆ Function

std::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, Functions::block, Functions::while_f

## Constructor & Destructor Documentation

## ◆ WTemplate()

Wt::WTemplate::WTemplate | ( | const WString & | text | ) |

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::TextFormat::XHTML textformat.

## Member Function Documentation

## ◆ addFunction()

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 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);
Wt::WTemplate
A widget that renders an XHTML template.
Definition WTemplate.h:185
Wt::WTemplate::Functions::block
static bool block(WTemplate *t, const std::vector< WString > &args, std::ostream &result)
A function that renders a macro block.
Wt::WTemplate::Functions::id
static bool id(WTemplate *t, const std::vector< WString > &args, std::ostream &result)
A function that resolves the id of a bound widget.
Wt::WTemplate::Functions::tr
static bool tr(WTemplate *t, const std::vector< WString > &args, std::ostream &result)
A function that resolves to a localized string.

## ◆ applyArguments()

virtual 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().

## ◆ bindEmpty()

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

Binds an empty string to a variable.

If a widget was bound to the variable, it is deleted first.

See also
  bindString()

## ◆ bindInt()

void Wt::WTemplate::bindInt | ( | const std::string & | varName,
|  | int | value )

Binds an integer value to a variable.

See also
  bindString()

## ◆ bindNew()

template<typename Widget , typename ... Args>

Widget * Wt::WTemplate::bindNew | ( | const std::string & | varName,
|  | Args &&... | args )

Creates a new widget with the given arguments, and binds it, returning a raw pointer.

This is implemented as:

std::unique_ptr<Widget> w{new Widget(std::forward<Args>(args)...)};
Widget *result = w.get();
bindWidget(varName, std::unique_ptr<WWidget>(std::move(w)));
return result;
Wt::WTemplate::bindWidget
virtual void bindWidget(const std::string &varName, std::unique_ptr< WWidget > widget)
Binds a widget to a variable.

This is a useful shorthand for creating and binding a widget in one go.

## ◆ bindString()

virtual void Wt::WTemplate::bindString | ( | const std::string & | varName,
|  | const WString & | value,
|  | TextFormat | textFormat = TextFormat::XHTML )
| virtual

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`, the `value` is validated according as for a WText. The default (TextFormat::XHTML) filters "active" content, to avoid XSS-based security risks.

See also
  bindWidget(), bindInt()
  resolveString(const std::string&)

## ◆ bindWidget() [1/2]

template<typename Widget >

Widget * Wt::WTemplate::bindWidget | ( | const std::string & | varName,
|  | std::unique_ptr< Widget > | widget )

Binds a widget to a variable, returning a raw pointer.

This is implemented as:

Widget *result = widget.get();
bindWidget(varName, std::unique_ptr<WWidget>(std::move(widget)));
return result;

## ◆ bindWidget() [2/2]

virtual void Wt::WTemplate::bindWidget | ( | const std::string & | varName,
|  | std::unique_ptr< WWidget > | widget )
| virtual

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 the `widget` must not yet be bound to another variable.

The widget is reparented to the WTemplate, so that it is deleted when the WTemplate 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 `nullptr` `widget`, which will resolve to an empty string.

See also
  bindString()
  resolveWidget()

## ◆ clear()

virtual void Wt::WTemplate::clear | ( |  | ) |
| virtual

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()

## ◆ conditionValue()

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

Returns a condition value.

See also
  setCondition()

## ◆ enableAjax()

virtual void Wt::WTemplate::enableAjax | ( |  | ) |
| overrideprotectedvirtual

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.

## ◆ encodeTemplateText()

bool Wt::WTemplate::encodeTemplateText | ( |  | ) | const

Returns whether internal path encoding is done on the template text.

See also
  setEncodeTemplateText()

## ◆ format() [1/2]

void Wt::WTemplate::format | ( | std::ostream & | result,
|  | const std::string & | s,
|  | TextFormat | textFormat = TextFormat::Plain )
| 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.

## ◆ format() [2/2]

void Wt::WTemplate::format | ( | std::ostream & | result,
|  | const WString & | s,
|  | TextFormat | textFormat = TextFormat::Plain )
| 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.

## ◆ getErrorText()

std::string Wt::WTemplate::getErrorText | ( |  | ) |

Renders the errors during renderring.

See also
  renderTemplateText()

## ◆ handleUnresolvedVariable()

virtual 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()

## ◆ hasInternalPathEncoding()

bool Wt::WTemplate::hasInternalPathEncoding | ( |  | ) | const

Returns whether internal paths are enabled.

See also
  setInternalPathEncoding()

## ◆ refresh()

virtual void Wt::WTemplate::refresh | ( |  | ) |
| overridevirtual

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 reimplemented refresh() to attach to it an effect).

Reimplemented from Wt::WWebWidget.

## ◆ removeWidget() [1/3]

std::unique_ptr< WWidget > Wt::WTemplate::removeWidget | ( | const std::string & | varName | ) |

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`, `nullptr` is returned.

## ◆ removeWidget() [2/3]

template<typename Widget >

std::unique_ptr< Widget > Wt::WWidget::removeWidget | ( | Widget * | widget | ) |

Removes a child widget.

This is an overload that automatically casts the returned value to a unique_ptr<Widget> for convenience

This is implemented as:

return std::unique_ptr<Widget>(static_cast<Widget*>(removeWidget(static_cast<WWidget*>(widget)).release()));
Wt::WTemplate::removeWidget
std::unique_ptr< WWidget > removeWidget(const std::string &varName)
Unbinds a widget by variable name.
Wt::WWidget
The abstract base class for a user-interface component.
Definition WWidget.h:66

## ◆ removeWidget() [3/3]

virtual std::unique_ptr< WWidget > Wt::WTemplate::removeWidget | ( | WWidget * | widget | ) |
| overridevirtual

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, `nullptr` is returned.

Reimplemented from Wt::WWidget.

## ◆ renderTemplate()

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

Renders the template into the given result stream.

The default implementation will call renderTemplateText() with the templateText().

## ◆ renderTemplateText()

bool Wt::WTemplate::renderTemplateText | ( | std::ostream & | result,
|  | const WString & | templateText )

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 also
  getErrorText()

## ◆ reset()

void Wt::WTemplate::reset | ( |  | ) |
| protected

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 the WTemplate if it has changed with a call to reset().

## ◆ resolve()

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 dynamic casts the result to type `T`. You may use this method to fetch widgets that have previously been bound using bindWidget().

If the cast fails, a null pointer is returned.

## ◆ resolveFunction()

virtual 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()

## ◆ resolveString()

virtual 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()

## ◆ resolveStringValue()

virtual const WString & Wt::WTemplate::resolveStringValue | ( | const std::string & | varName | ) |
| virtual

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(const std::string&, const std::vector<WString>&, std::ostream&) which resolves any variable to a string (both strings and widgets alike).

## ◆ resolveWidget()

virtual 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 (Wt::WWidget *known = WTemplate::resolveWidget(varName)) {
return known;
} else {
if (varName == "age-input") {
// widget only created when used
return bindWidget(varName, std::make_unique<Wt::WLineEdit>());
}
return nullptr;
}
Wt::WTemplate::resolveWidget
virtual WWidget * resolveWidget(const std::string &varName)
Resolves a widget for a variable name.

## ◆ setCondition()

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`.

## ◆ setEncodeTemplateText()

void Wt::WTemplate::setEncodeTemplateText | ( | bool | 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`

## ◆ setInternalPathEncoding()

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()

## ◆ setTemplateText()

void Wt::WTemplate::setTemplateText | ( | const WString & | text,
|  | TextFormat | textFormat = TextFormat::XHTML )

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

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

See also
  clear()

## ◆ setWidgetIdMode()

void Wt::WTemplate::setWidgetIdMode | ( | TemplateWidgetIdMode | mode | ) |

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.

## ◆ templateText()

virtual WString Wt::WTemplate::templateText | ( |  | ) | const
| virtual

Returns the template.

See also
  setTemplateText()

## ◆ widgetIdMode()

TemplateWidgetIdMode Wt::WTemplate::widgetIdMode | ( |  | ) | const

Returns how the varName is reflected on a bound widget.

See also
  setWidgetIdMode()