Marcel van Lohuizen | 3e592b4 | 2019-01-11 20:31:29 +0100 | [diff] [blame] | 1 | [TOC](Readme.md) [Prev](lists.md) [Next](instances.md) |
| 2 | |
| 3 | _Types ~~and~~ are Values_ |
| 4 | |
| 5 | # Templates |
| 6 | |
Jonathan Amsterdam | e479038 | 2019-01-20 10:29:29 -0500 | [diff] [blame] | 7 | <!-- jba: this is not in the spec, aside from the TemplateLabel grammar rule. --> |
| 8 | |
Marcel van Lohuizen | 3e592b4 | 2019-01-11 20:31:29 +0100 | [diff] [blame] | 9 | One of CUE's most powerful features is templates. |
Dr. Stefan Schimanski | 8e43045 | 2019-05-16 21:16:21 +0000 | [diff] [blame] | 10 | A template defines a value to be unified with each field of a struct. |
Marcel van Lohuizen | 3e592b4 | 2019-01-11 20:31:29 +0100 | [diff] [blame] | 11 | |
| 12 | The template's identifier (in angular brackets) is bound to name of each |
| 13 | of its sibling fields and is visible within the template value |
| 14 | that is unified with each of the siblings. |
| 15 | |
Marcel van Lohuizen | f0c9404 | 2019-02-22 22:46:37 +0100 | [diff] [blame] | 16 | <!-- CUE editor --> |
| 17 | _templates.cue:_ |
Marcel van Lohuizen | 3e592b4 | 2019-01-11 20:31:29 +0100 | [diff] [blame] | 18 | ``` |
| 19 | // The following struct is unified with all elements in job. |
| 20 | // The name of each element is bound to Name and visible in the struct. |
| 21 | job <Name>: { |
| 22 | name: Name |
Marcel van Lohuizen | c9b3cb2 | 2019-01-30 11:32:41 +0100 | [diff] [blame] | 23 | replicas: uint | *1 |
Marcel van Lohuizen | 3e592b4 | 2019-01-11 20:31:29 +0100 | [diff] [blame] | 24 | command: string |
| 25 | } |
| 26 | |
| 27 | job list command: "ls" |
| 28 | |
| 29 | job nginx: { |
| 30 | command: "nginx" |
| 31 | replicas: 2 |
| 32 | } |
| 33 | ``` |
| 34 | |
Marcel van Lohuizen | f0c9404 | 2019-02-22 22:46:37 +0100 | [diff] [blame] | 35 | <!-- JSON result --> |
| 36 | `$ cue eval templates.cue` |
Marcel van Lohuizen | 3e592b4 | 2019-01-11 20:31:29 +0100 | [diff] [blame] | 37 | ``` |
| 38 | job: { |
| 39 | list: { |
| 40 | name: "list" |
| 41 | replicas: 1 |
| 42 | command: "ls" |
| 43 | } |
| 44 | nginx: { |
| 45 | name: "nginx" |
| 46 | replicas: 2 |
| 47 | command: "nginx" |
| 48 | } |
| 49 | } |
Jonathan Amsterdam | e479038 | 2019-01-20 10:29:29 -0500 | [diff] [blame] | 50 | ``` |