Template inclusion - misonou/waterpipe GitHub Wiki
Templates can be predefined elsewhere and be included on use.
To make a template available for inclusion, defined the template on waterpipe.pipes:
waterpipe.pipes.myTemplate = 'The value is {{value}}.';In such sense a template is considered as a parameterless pipe function. Therefore it is the same to include the template than to invoke a pipe function.
{{value}} ➜ foo
{{myTemplate}} ➜ The value is foo.
{{obj.value}} ➜ bar
{{obj myTemplate}} ➜ The value is bar.
When using waterpipe in HTML document, any <script> tag with type text/x-waterpipe
will be automatically setup on waterpipe.pipes.
<script type="text/x-waterpipe" id="myTemplate">
The value is {{value}}.
</script>A template is considered single-valued if there is
- only one evaluated output throughout execution; and
- only consist of whitespace characters in non-evaluated output.
If such case, including these templates as pipe functions, the evaluated value can be used for conditional testing, iteration, or chained to the next pipe function without being stringified.
waterpipe.pipes.positive = '{{value > 0}}';
waterpipe.pipes.addOneEach = '{{map [ + 1 ]}}';{{value}} ➜ -1
{{if value positive}}
positive
{{else}}
negative ➜ negative
{{/if}}
{{arr}} ➜ [1,2,3]
{{foreach arr addOneEach}}
{{.}} ➜ 2 ➜ 3 ➜ 4
{{/foreach}}
Prior to version 2.1, the first example outputs "positive" instead because {{value positive}} returns stringified "false" instead of boolean false; while in the second sample the loop would not print anything because {{foreach}} construct does not iterate on string values.
Since version 2.8, it is possible to evaluate template stored in data object using the eval pipe function.
For example given the following data:
{ value: 1, template: "The value is {{.}}." }{{value |> template}} ➜ The value is 1.