Templates
Templates provide a simple way of content generation using well-known Razor language syntax (see cheat-sheet below). They are very useful for generating content like email notifications, documents, contracts, etc.
Creating a template
Template code language
This setting is primarily about developer's comfort during preparation of a template.
Language | Syntax highlighting | Preview | Usage |
---|---|---|---|
None | No | No | Arbitrary strings you need to generate. |
Html | HTML + Razor | Yes | Html pages, snippets. Useful for emails. |
Markdown | MD + Razor | Yes | Markdown texts, usually converted into HTML later. |
Model type
Model type defines input which the template receives. It's available as Model variable inside the model.
Type | C# type of Model | Usage |
---|---|---|
Object | Object | Arbitrary models, often used for custom classes or for templates without a model |
String | String | Useful for nesting templates |
String Enumerable | IEnumerable<string> | Useful for nesting templates |
Entity | EntityType | Templates for entity |
Entity Enumerable | IEnumerable<EntityType> | Templates for entity collection |
Aspect | AspectType | Templates for entity inheriting an aspect |
Aspect Enumerable | IEnumerable<AspectType> | Templates for collection of entities which inherit an aspect |
Usage
Every template you define is accessible through App.Templates object. Each template has a Render(model) method which requires different input based on selected Model Type.
MyEntity entity = db.MyEntitySet.First();
string rendered = App.Templates.MyTemplate.Render(entity);
Master template
Common use-case of templates is that you have one master template which contains eg. common header and footer and then generate inner content with various smaller templates. This setup is usually done by using String model template which acts as a Master. Inside this master template is following code:
...proceeding content...
@Html.Raw(Model)
...succeeding content...
Then you use the master template like this:
// Inner content
MyEntity entity = db.MyEntitySet.First();
string rendered = App.Templates.MyTemplate.Render(entity);
string wholePage = App.Templates.MyMasterTemplate.Render(rendered);
Razor language
Razor language is templating language which allows you to embed custom logic into a template. With Razor you can add loops, conditions and even custom C# code.
Syntax/Sample | Razor |
---|---|
Mixing expressions and text |
|
Expression (Html Encoded) |
|
Expression (Unencoded) |
|
Explicit Expression |
|
Calling method |
|
Iteration rendering |
|
Conditional rendering |
|
Escaping the @ sign |
|
Accessing the resources
You can access app resources in Razor code. Below is a simple example of how to include an image in a template:
<img class="container" src="data:image/png;base64,@App.Resources.my_image_jpg"/>