@@ -118,6 +118,85 @@ recognized:
118
118
struct HelloTemplate <'a > { ... }
119
119
```
120
120
121
+ ## Templating ` enum ` s
122
+
123
+ You can add derive ` Template ` s for ` struct ` s and ` enum ` s.
124
+ If you add ` #[template()] ` only to the item itself, both item kinds work exactly the same.
125
+ But with ` enum ` s you also have the option to add a specialized implementation to one, some,
126
+ or all variants:
127
+
128
+ ``` rust
129
+ #[derive(Debug , Template )]
130
+ #[template(path = " area.txt" )]
131
+ enum Area {
132
+ Square (f32 ),
133
+ Rectangle { a : f32 , b : f32 },
134
+ Circle { radius : f32 },
135
+ }
136
+ ```
137
+
138
+ ``` jinja2
139
+ {%- match self -%}
140
+ {%- when Self::Square(side) -%}
141
+ {{side}}^2
142
+ {%- when Self::Rectangle { a, b} -%}
143
+ {{a}} * {{b}}
144
+ {%- when Self::Circle { radius } -%}
145
+ pi * {{radius}}^2
146
+ {%- endmatch -%}
147
+ ```
148
+
149
+ will give you the same results as:
150
+
151
+ ``` rust
152
+ #[derive(Template , Debug )]
153
+ #[template(ext = " txt" )]
154
+ enum AreaPerVariant {
155
+ #[template(source = " {{self.0}}^2" )]
156
+ Square (f32 ),
157
+ #[template(source = " {{a}} * {{b}}" )]
158
+ Rectangle { a : f32 , b : f32 },
159
+ #[template(source = " pi * {{radius}}^2" )]
160
+ Circle { radius : f32 },
161
+ }
162
+ ```
163
+
164
+ As you can see with the ` ext ` attribute, ` enum ` variants inherit most settings of the ` enum ` :
165
+ ` config ` , ` escape ` , ` ext ` , ` syntax ` , and ` whitespace ` .
166
+ Not inherited are: ` block ` , and ` print ` .
167
+
168
+ If there is no ` #[template] ` annotation for an ` enum ` variant,
169
+ then the ` enum ` needs a default implementation, which will be used if ` self ` is this variant.
170
+ A good compromise between annotating only the template, or all its variants,
171
+ might be using the ` block ` argument on the members:
172
+
173
+ ``` rust
174
+ #[derive(Template , Debug )]
175
+ #[template(path = " area.txt" )]
176
+ enum AreaWithBlocks {
177
+ #[template(block = " square" )]
178
+ Square (f32 ),
179
+ #[template(block = " rectangle" )]
180
+ Rectangle { a : f32 , b : f32 },
181
+ #[template(block = " circle" )]
182
+ Circle { radius : f32 },
183
+ }
184
+ ```
185
+
186
+ ``` jinja2
187
+ {%- block square -%}
188
+ {{self.0}}^2
189
+ {%- endblock -%}
190
+
191
+ {%- block rectangle -%}
192
+ {{a}} * {{b}}
193
+ {%- endblock -%}
194
+
195
+ {%- block circle -%}
196
+ pi * {{radius}}^2
197
+ {%- endblock -%}
198
+ ```
199
+
121
200
## Documentation as template code
122
201
[ #documentation-as-template-code ] : #documentation-as-template-code
123
202
0 commit comments