|
| 1 | +--- |
| 2 | +title: Defining a function |
| 3 | +tags: [template, features] |
| 4 | +--- |
| 5 | +## Overview |
| 6 | + |
| 7 | +A template function is a function defined inside a template that can render content dynamically. When passed as an argument to another function (like map, each, or custom helpers), it acts as a kind of callback, formatting or transforming values within the template itself. |
| 8 | + |
| 9 | +You define a template block or lambda that takes arguments and renders something with them. Then you pass that function to another function (e.g., a mapping function or loop). |
| 10 | + |
| 11 | +## Registering a Function |
| 12 | + |
| 13 | +To register a function, use the `AddFunction` method of an `ITemplateEngine`. The method requires: |
| 14 | + |
| 15 | +- A name for the function – the identifier for the function. |
| 16 | +- A function returning a string representing the function template. |
| 17 | + |
| 18 | +```csharp |
| 19 | +var factory = new FileBasedTemplateEngineFactory(); |
| 20 | +var engine = factory.GetByTag(tag); |
| 21 | +engine.AddFunction("Hello", () => "function definition"); |
| 22 | +``` |
| 23 | + |
| 24 | +## Using Functions in Templates |
| 25 | + |
| 26 | +Once registered, functions can be applied directly in templates by referencing the function name and passing values to the parameters. All examples below will have the same output: |
| 27 | + |
| 28 | +```text |
| 29 | +Greetings: Mr. Einstein Albert! |
| 30 | +``` |
| 31 | + |
| 32 | +### Scriban |
| 33 | + |
| 34 | +The main template is defined as, |
| 35 | + |
| 36 | +```liquid |
| 37 | +{% raw %}Greetings: {{ Hello(model.Name.First, model.Name.Last) }}!{% endraw %} |
| 38 | +``` |
| 39 | + |
| 40 | +and the function itself is defined as, |
| 41 | + |
| 42 | +```text |
| 43 | +{%- raw -%} |
| 44 | +{{ func Hello(firstName, lastName) -}} |
| 45 | + Mr. {{ lastName }} {{ firstName -}} |
| 46 | +{{ end }} |
| 47 | +{% endraw %} |
| 48 | +``` |
| 49 | + |
| 50 | +### StringTemplate |
| 51 | + |
| 52 | +The main template is defined as, |
| 53 | + |
| 54 | +```text |
| 55 | +{% raw %}Greetings: <Hello(model.Name.First, model.Name.Last)>!{% endraw %} |
| 56 | +``` |
| 57 | + |
| 58 | +and the function itself is defined as, |
| 59 | + |
| 60 | +```text |
| 61 | +{% raw %}Hello(firstName, lastName)::= Mr. <lastName> <firstName>{% endraw %} |
| 62 | +``` |
| 63 | + |
| 64 | +### Liquid, Fluid, Handlebars, Morestachio and SmartFormat |
| 65 | + |
| 66 | +This feature is not supported. |
| 67 | + |
| 68 | +### Conclusions |
| 69 | + |
| 70 | +Template functions that accept another template function give you a clean, composable way to define how data should be rendered, and reuse that rendering logic flexibly. |
0 commit comments