HTML Templates
WebSharper.UI's syntax for creating HTML is compact and convenient, but sometimes you do need to include a plain HTML file in a project. It is much more convenient for designing to have a .html file that you can touch up and reload your application without having to recompile it. This is what Templates provide. Templates are HTML files that can be loaded by WebSharper.UI, and augmented with special elements and attributes that provide additional functionality:
- Declaring Holes for nodes, attributes and event handlers that can be filled at runtime by F# code;
- Declaring two-way binding between F# Vars and HTML input elements (see reactive);
- Declaring inner Templates, smaller HTML widgets within the page, that can be instantiated dynamically.
All of these are parsed from HTML at compile time and provided as F# types and methods, ensuring that your templates are correct.
Basics
To declare a template, use the Template type provider from the namespace WebSharper.UI.Templating.
To instantiate it, call your type's constructor and then its .Doc() method.
my-template.html:
equivalent to:
Note that the template doesn't have to be a full HTML document, but can simply be a snippet or sequence of snippets. This is particularly useful to build a library of widgets using inner templates.
If the template comprises a single HTML element, then an additional method .Elt() is available. It is identical to .Doc(), except its return value has type Elt instead of Doc.
You can also declare a template from multiple files at once using a comma-separated list of file names. In this case, the template for each file is a nested class named after the file, truncated of its file extension.
my-template.html:
second-template.html:
equivalent to:
Holes
You can add holes to your template that will be filled by F# code. Each hole has a name. To fill a hole in F#, call the method with this name on the template instance before finishing with .Doc().
-
${HoleName}creates astringhole. You can use it in text or in the value of an attribute.my-template.html:
Result:
On the client side, this hole can also be filled with a
View<string>(see reactive) to include dynamically updated text content. -
The attribute
ws-replacecreates aDocorseq<Doc>hole. The element on which this attribute is set will be replaced with the provided Doc(s). The name of the hole is the value of thews-replaceattribute.my-template.html:
Result:
-
The attribute
ws-holecreates aDocorseq<Doc>hole. The element on which this attribute is set will have its contents replaced with the provided Doc(s). The name of the hole is the value of thews-holeattribute.my-template.html:
Result:
-
The attribute
ws-attrcreates anAttrorseq<Attr>hole. The name of the hole is the value of thews-attrattribute.my-template.html:
Result:
-
The attribute
ws-varcreates aVarhole (see reactive) that is bound to the element. It can be used on the following elements:<input>,<textarea>,<select>, for which it creates aVar<string>hole.<input type="number">, for which it creates a hole that can be one of the following types:Var<int>,Var<float>,Var<CheckedInput<int>>,Var<CheckedInput<float>>.<input type="checkbox">, for which it creates aVar<bool>hole.
The name of the hole is the value of the
ws-varattribute. Text${Hole}s with the same name can be used, and they will dynamically match the value of the Var.my-template.html:
Result:
If you don't fill the hole (ie you don't call
.Name(varName)above), theVarwill be implicitly created, so${Name}will still be dynamically updated from the user's input. -
The attribute
ws-onclick(or any other event name instead ofclick) creates an event handler hole of typeTemplateEvent -> unit. The argument of typeTemplateEventhas the following fields:Target: Dom.Elementis the element itself.Event: Dom.Eventis the event triggered.Varshas a field for each of theVars associated tows-vars in the template.Anchorshas a field for each of the elements associated tows-anchors andws-doms in the template.
my-template.html:
-
The attribute
ws-anchormarks an element to be exposed by the type provider under the.Anchorsproperty of aTemplateEventwith the typeDom.Element. This can be used instead ofJS.Document.QuerySelectorto look up elements in a statically typed way that's tied to the template. -
The attribute
ws-domis similar tows-anchor, it also creates a property under.Anchors, hovewer with the typeVar<option<Dom.Element>>. ThisVarcan be used to dynamically access, remove, or set the element replacing the original. -
The attribute
ws-preservemarks the element to be exempt from WebSharper template parsing on the server side. This can be used to serve templates in HTML to be used by the client side.
Filling holes
There are two ways to fill the content for a given hole.
-
The recommended way is by using the method with the hole's name on the template instance, as used in the examples above.
-
If you need to decide which hole to fill at runtime, you can use the method
.With(holeName, content). It will throw a runtime error if the content's type doesn't match the hole's type. -
You can of course mix and match both styles.
Using HTML5 templates
As an alternative, the standard HTML5 template tags are also recognized.
A template tag with an id is equivalent to using ws-children-template, it uses the contents of the element to create the template.
An element with a slot attribute is equivalent to using ws-hole, it defines an element to which content is inserted into. The name attribute is used by the type provider to create the method for filling it in, or if not present (default slot), it will be available as .Default.
Inner templates
To create a template for a widget (as opposed to a full page), you can put it in its own dedicated template file, but another option is to make it an inner template. An inner template is a smaller template declared inside a template file using the following syntax:
- The
ws-templateattribute declares that its element is a template whose name is the value of this attribute. - The
ws-children-templateattribute declares that the children of its element is a template whose name is the value of this attribute.
Inner templates are available in F# as a nested class under the main provided type.
my-template.html:
Result:
Instantiating templates in HTML
You can also instantiate a template within another template, entirely in HTML, without the need for F# to glue them together.
A node named <ws-TemplateName> instantiates the inner template TemplateName from the same file. A node named <ws-fileName.TemplateName> instantiates the inner template TemplateName from the file fileName. The file name is the same as the generated class name, so with file extension excluded.
Child elements of the <ws-*> fill holes. These elements are named after the hole they fill.
${Text}holes are filled with the text content of the element.ws-holeandws-replaceholes are filled with the HTML content of the element.ws-attrholes are filled with the attributes of the element.- Other types of holes cannot be directly filled like this.
Additionally, attributes on the <ws-*> element itself define hole mappings. That is to say, <ws-MyTpl Inner="Outer"> fills the hole named Inner of the template MyTpl with the value of the hole Outer of the containing template. As a shorthand, <ws-MyTpl Attr> is equivalent to <ws-MyTpl Attr="Attr">.
Any holes that are neither mapped by an attribute nor filled by a child element are left empty.
The following example is equivalent to the example from Inner Templates:
my-template.html:
Controlling the loading of templates
The type provider can be parameterized to control how its contents are loaded both on the server and the client. For example:
The possible values for clientLoad are:
-
ClientLoad.Inline(default): The template is included in the compiled JavaScript code, and any change tomy-template.htmlrequires a recompilation to be reflected in the application. -
ClientLoad.FromDocument: The template is loaded from the DOM. This means thatmy-template.htmlmust be the document in which the code is run: either directly served as a Single-Page Application, or passed toContent.Pagein a Client-Server Application.In this mode, it doesn't make sense for client-side code to instantiate the full template, since you are already inside the document. But the following are possible:
The possible values for serverLoad are:
-
ServerLoad.WhenChanged(default): The runtime sets up a file watcher on the template file, and reloads it whenever it is edited. -
ServerLoad.Once: The template file is loaded on first use and never reloaded. -
ServerLoad.PerRequest: The template file is reloaded every time it is needed. We recommend against this option for performance reasons.
Binding directly to the DOM
When using a template from the client side that is declared with clientLoad = ClientLoad.FromDocument, you can directly bind content, Vars, etc. to the DOM. Instead of calling .Doc() to create a Doc, use .Bind(), which returns unit, to just apply the template to the current document.
index.html:
Result:
Note that for Bind() to work correctly, the holes need to be present in the document itself. This is not a problem if your project is an SPA. But you can also serve the page from a sitelet, using the same template on the server side. You can fill some holes on the server side and leave some to be filled by the client side. However, by default, the server-side engine removes unfilled holes from the served document. This is correct behavior in most cases, but here, the client does need the unfilled hole markers like ws-replace or ${...} to be present. So this behavior can be overridden by the optional boolean argument keepUnfilled of the .Doc() and .Elt() methods.
index.html:
Served page:
Result after Client.Startup() has run:
Accessing the template's model
Templates allow you to access their "model", ie the set of all the reactive Vars that are bound to it, whether passed explicitly or automatically created for its ws-vars. It is accessible in two ways:
-
In event handlers, it is available as the
Varsproperty of the handler argument. -
From outside the template: instead of finishing the instanciation of a template with
.Doc(), you can call.Create(). This will return aTemplateInstancewith the properties:.Doc, which returns the template itself (also.Eltif the template is a single element), and.Vars, which contains the vars. This method is only available when instantiating the template from the client side.my-template.html:
Result:
Mixing client code in server-side templates
It is possible to include some client-side functionality when creating a template on the server side.
-
If you use
ws-var="VarName", the corresponding Var will be created on the client on page startup. However, passing a Var using.VarName(myVar)is not possible, since it would be a server-side Var. -
Event handlers (such as
ws-onclick="EventName") work fully if you pass an anonymous function:.EventName(fun e -> ...). The body of this function will be compiled to JavaScript. You can also pass a top-level function, in this case it must be declared with[<JavaScript>].This also includes
ws-onafterrender, which causes the given function to be called on page startup.
Special holes in server-side templates
In a server-side template, you must specify the location of where WebSharper can include its generated content. Three special placeholders are provided to include client-side content in the page:
scriptsis replaced with the JavaScript files required by the client-side code included in the page (including WebSharper-generated.jsfiles). Usage:<script ws-replace="scripts"></script>stylesis replaced with the CSS files required by the client-side code included in the page. Usage:<link ws-replace="styles" />metais replaced with a<meta>tag that contains initialization data for client-side controls. Usage:<meta ws-replace="meta" />
The scripts hole is necessary for correct working of the served page if it contains any client-side WebSharper functionality.
The other two are optional: if neither styles nor meta is provided explicilty, then they are included automatically above the content for scripts.
Dynamic templates
It is also possible to create a template without the compile-time safety of the type provider. This is done using the type DynamicTemplate.
This type can be used similarly to Template<...>, with the following limitations:
- It is server-side only.
- Its constructor must receive the HTML source as a string.
- Holes can only be filled with
.With(holeName, content). - The final instantiation must be done with
.Doc().
Sample
This sample demonstrates:
- Using
ws-templateto define a reusable HTML structure. - Binding data to HTML inputs with
ws-var, displaying text via the${Hole}syntax. - Handling events like clicks with
ws-onclick. - Creating and using a
ListModelfor dynamic lists.