0
# HTML Templates
1
2
Template system using tagged template literals with efficient compilation, directive support, and reactive binding capabilities for building dynamic HTML content.
3
4
## Capabilities
5
6
### HTML Template Tag
7
8
Tagged template literal function for creating reactive HTML templates with binding expressions and directives.
9
10
```typescript { .api }
11
/**
12
* Transforms a template literal string into a ViewTemplate
13
* @param strings - The string fragments that are interpolated with the values
14
* @param values - The values that are interpolated with the string fragments
15
* @returns A ViewTemplate instance
16
*/
17
function html<TSource = any, TParent = any>(
18
strings: TemplateStringsArray,
19
...values: TemplateValue<TSource, TParent>[]
20
): ViewTemplate<TSource, TParent>;
21
22
/**
23
* Template tag interface with additional utilities
24
*/
25
interface HTMLTemplateTag {
26
<TSource = any, TParent = any>(
27
strings: TemplateStringsArray,
28
...values: TemplateValue<TSource, TParent>[]
29
): ViewTemplate<TSource, TParent>;
30
31
/** Creates partial HTML directive for template composition */
32
partial(html: string): InlineTemplateDirective;
33
}
34
35
/**
36
* Types that can be interpolated into templates
37
*/
38
type TemplateValue<TSource, TParent = any> =
39
| Expression<TSource, any, TParent>
40
| Binding<TSource, any, TParent>
41
| HTMLDirective
42
| CaptureType<TSource, TParent>;
43
```
44
45
**Usage Examples:**
46
47
```typescript
48
import { FASTElement, customElement, html, attr } from "@microsoft/fast-element";
49
50
// Basic template with bindings
51
const template = html<MyElement>`
52
<div class="container">
53
<h1>${x => x.title}</h1>
54
<p>${x => x.description}</p>
55
<button @click="${x => x.handleClick}">
56
${x => x.buttonText}
57
</button>
58
</div>
59
`;
60
61
// Template with conditional content
62
const conditionalTemplate = html<UserCard>`
63
<div class="user-card">
64
<h2>${x => x.name}</h2>
65
${x => x.showEmail ? html`<p>${x => x.email}</p>` : ""}
66
${x => x.avatar ? html`<img src="${x => x.avatar}" alt="Avatar">` : ""}
67
</div>
68
`;
69
70
// Template composition with partials
71
const headerPartial = html.partial(`
72
<header class="app-header">
73
<nav>Navigation</nav>
74
</header>
75
`);
76
77
const mainTemplate = html`
78
${headerPartial}
79
<main>
80
<slot></slot>
81
</main>
82
`;
83
84
@customElement({
85
name: "my-element",
86
template
87
})
88
export class MyElement extends FASTElement {
89
@attr title: string = "Hello World";
90
@attr description: string = "A sample element";
91
@attr buttonText: string = "Click me";
92
93
handleClick() {
94
console.log("Button clicked!");
95
}
96
}
97
```
98
99
### ViewTemplate Class
100
101
Core template class that manages HTML content, compilation, and view creation with support for both element and synthetic views.
102
103
```typescript { .api }
104
/**
105
* A template capable of creating HTMLView instances or rendering directly to DOM
106
*/
107
class ViewTemplate<TSource = any, TParent = any>
108
implements ElementViewTemplate<TSource, TParent>, SyntheticViewTemplate<TSource, TParent> {
109
110
/** The html representing what this template will instantiate */
111
readonly html: string | HTMLTemplateElement;
112
113
/** The directives that will be connected to placeholders in the html */
114
readonly factories: Record<string, ViewBehaviorFactory>;
115
116
/**
117
* Creates an instance of ViewTemplate
118
* @param html - The html string or template element
119
* @param factories - The directive factories
120
* @param policy - The security policy for compilation
121
*/
122
constructor(
123
html: string | HTMLTemplateElement,
124
factories?: Record<string, ViewBehaviorFactory>,
125
policy?: DOMPolicy
126
);
127
128
/** Creates an HTMLView instance based on this template definition */
129
create(hostBindingTarget?: Element): HTMLView<TSource, TParent>;
130
131
/** Returns a directive that can inline the template */
132
inline(): CaptureType<TSource, TParent>;
133
134
/**
135
* Sets the DOMPolicy for this template
136
* @param policy - The policy to associate with this template
137
* @returns The modified template instance
138
*/
139
withPolicy(policy: DOMPolicy): this;
140
141
/**
142
* Creates an HTMLView from this template, binds it to the source, and appends it to the host
143
* @param source - The data source to bind the template to
144
* @param host - The Element where the template will be rendered
145
* @param hostBindingTarget - An HTML element to target the host bindings at
146
*/
147
render(
148
source: TSource,
149
host: Node,
150
hostBindingTarget?: Element
151
): HTMLView<TSource, TParent>;
152
153
/**
154
* Creates a template based on static strings and dynamic values
155
* @param strings - The static strings to create the template with
156
* @param values - The dynamic values to create the template with
157
* @param policy - The DOMPolicy to associate with the template
158
* @returns A ViewTemplate
159
*/
160
static create<TSource = any, TParent = any>(
161
strings: string[],
162
values: TemplateValue<TSource, TParent>[],
163
policy?: DOMPolicy
164
): ViewTemplate<TSource, TParent>;
165
}
166
```
167
168
**Usage Examples:**
169
170
```typescript
171
import { ViewTemplate, html, DOMPolicy } from "@microsoft/fast-element";
172
173
// Create template manually
174
const manualTemplate = new ViewTemplate(
175
`<div class="manual">\${0}</div>`,
176
{
177
"0": /* factory */
178
}
179
);
180
181
// Create with security policy
182
const secureTemplate = html`
183
<div innerHTML="${x => x.userContent}"></div>
184
`.withPolicy(myDOMPolicy);
185
186
// Render template directly
187
const view = template.render(
188
{ title: "Hello", content: "World" },
189
document.body
190
);
191
192
// Create reusable view
193
const reusableView = template.create();
194
reusableView.bind({ title: "Dynamic" });
195
reusableView.appendTo(container);
196
197
// Template composition
198
const childTemplate = html`<span>${x => x.text}</span>`;
199
const parentTemplate = html`
200
<div class="parent">
201
${childTemplate.inline()}
202
</div>
203
`;
204
```
205
206
### Element View Template
207
208
Specialized template interface for custom elements with host binding support and element-specific rendering capabilities.
209
210
```typescript { .api }
211
/**
212
* A template capable of creating views specifically for rendering custom elements
213
*/
214
interface ElementViewTemplate<TSource = any, TParent = any> {
215
/**
216
* Creates an ElementView instance based on this template definition
217
* @param hostBindingTarget - The element that host behaviors will be bound to
218
*/
219
create(hostBindingTarget: Element): ElementView<TSource, TParent>;
220
221
/**
222
* Creates an HTMLView from this template, binds it to the source, and appends it to the host
223
* @param source - The data source to bind the template to
224
* @param host - The Node where the template will be rendered
225
* @param hostBindingTarget - An HTML element to target the host bindings at
226
*/
227
render(
228
source: TSource,
229
host: Node,
230
hostBindingTarget?: Element
231
): ElementView<TSource, TParent>;
232
}
233
234
/**
235
* Hydratable version of element view template for SSR scenarios
236
*/
237
interface HydratableElementViewTemplate<TSource = any, TParent = any>
238
extends ElementViewTemplate<TSource, TParent> {
239
/**
240
* Hydrates an element view from server-rendered content
241
* @param firstChild - First child node of the hydration range
242
* @param lastChild - Last child node of the hydration range
243
* @param hostBindingTarget - The element that host behaviors will be bound to
244
*/
245
hydrate(
246
firstChild: Node,
247
lastChild: Node,
248
hostBindingTarget?: Element
249
): ElementView<TSource, TParent>;
250
}
251
```
252
253
### Synthetic View Template
254
255
Template interface for creating views not connected to custom elements, useful for dynamic content and template fragments.
256
257
```typescript { .api }
258
/**
259
* A template capable of rendering views not specifically connected to custom elements
260
*/
261
interface SyntheticViewTemplate<TSource = any, TParent = any> {
262
/** Creates a SyntheticView instance based on this template definition */
263
create(): SyntheticView<TSource, TParent>;
264
265
/** Returns a directive that can inline the template */
266
inline(): CaptureType<TSource, TParent>;
267
}
268
269
/**
270
* Hydratable version of synthetic view template for SSR scenarios
271
*/
272
interface HydratableSyntheticViewTemplate<TSource = any, TParent = any>
273
extends SyntheticViewTemplate {
274
/**
275
* Hydrates a synthetic view from server-rendered content
276
* @param firstChild - First child node of the hydration range
277
* @param lastChild - Last child node of the hydration range
278
*/
279
hydrate(firstChild: Node, lastChild: Node): SyntheticView<TSource, TParent>;
280
}
281
```
282
283
**Usage Examples:**
284
285
```typescript
286
import { html, SyntheticViewTemplate } from "@microsoft/fast-element";
287
288
// Synthetic template for dynamic content
289
const dynamicContent: SyntheticViewTemplate<DataItem> = html`
290
<div class="dynamic-item">
291
<h3>${x => x.title}</h3>
292
<p>${x => x.description}</p>
293
</div>
294
`;
295
296
// Create and use synthetic view
297
const syntheticView = dynamicContent.create();
298
syntheticView.bind(dataItem);
299
syntheticView.appendTo(container);
300
301
// Inline synthetic template
302
const listTemplate = html`
303
<ul class="item-list">
304
${repeat(x => x.items, dynamicContent.inline())}
305
</ul>
306
`;
307
```
308
309
### Template Compilation System
310
311
System for compiling templates into efficient view factories with directive resolution and binding optimization.
312
313
```typescript { .api }
314
/**
315
* The result of a template compilation operation
316
*/
317
interface HTMLTemplateCompilationResult<TSource = any, TParent = any> {
318
/**
319
* Creates a view instance
320
* @param hostBindingTarget - The host binding target for the view
321
*/
322
createView(hostBindingTarget?: Element): HTMLView<TSource, TParent>;
323
324
/** Compiled view behavior factories */
325
readonly factories: CompiledViewBehaviorFactory[];
326
}
327
328
/**
329
* Strategy for compiling templates
330
*/
331
interface CompilationStrategy {
332
/**
333
* Compiles a template
334
* @param template - The template to compile
335
* @param factories - The directive factories
336
* @param policy - The DOM security policy
337
*/
338
compile<TSource = any, TParent = any>(
339
template: string | HTMLTemplateElement,
340
factories: Record<string, ViewBehaviorFactory>,
341
policy?: DOMPolicy
342
): HTMLTemplateCompilationResult<TSource, TParent>;
343
}
344
345
/**
346
* Template compiler utilities
347
*/
348
const Compiler: {
349
/**
350
* Compiles a template into a compilation result
351
* @param html - The HTML template string or element
352
* @param factories - The directive factories
353
* @param policy - The DOM security policy
354
*/
355
compile<TSource = any, TParent = any>(
356
html: string | HTMLTemplateElement,
357
factories: Record<string, ViewBehaviorFactory>,
358
policy?: DOMPolicy
359
): HTMLTemplateCompilationResult<TSource, TParent>;
360
};
361
```
362
363
**Usage Examples:**
364
365
```typescript
366
import { Compiler, html, ViewTemplate } from "@microsoft/fast-element";
367
368
// Manual compilation
369
const result = Compiler.compile(
370
'<div>${0}</div>',
371
{ "0": bindingFactory },
372
domPolicy
373
);
374
375
// Create view from compilation result
376
const view = result.createView();
377
view.bind(source);
378
379
// Custom compilation strategy
380
class MyCompilationStrategy implements CompilationStrategy {
381
compile(template, factories, policy) {
382
// Custom compilation logic
383
return Compiler.compile(template, factories, policy);
384
}
385
}
386
```
387
388
### Inline Template Directive
389
390
Directive for composing templates by inlining HTML content with associated behavior factories.
391
392
```typescript { .api }
393
/**
394
* Inlines a template into another template
395
*/
396
class InlineTemplateDirective implements HTMLDirective {
397
/** An empty template partial */
398
static readonly empty: InlineTemplateDirective;
399
400
/**
401
* Creates an instance of InlineTemplateDirective
402
* @param html - The HTML template string to inline
403
* @param factories - The behavior factories associated with the template
404
*/
405
constructor(
406
html: string,
407
factories?: Record<string, ViewBehaviorFactory>
408
);
409
410
/**
411
* Creates HTML to be used within a template
412
* @param add - Can be used to add behavior factories to a template
413
*/
414
createHTML(add: AddViewBehaviorFactory): string;
415
}
416
```
417
418
**Usage Examples:**
419
420
```typescript
421
import { html, InlineTemplateDirective } from "@microsoft/fast-element";
422
423
// Create partial template
424
const buttonPartial = html.partial(`
425
<button class="btn" type="button">
426
<slot></slot>
427
</button>
428
`);
429
430
// Use partial in main template
431
const formTemplate = html`
432
<form>
433
<input type="text" placeholder="Enter text">
434
${buttonPartial}
435
</form>
436
`;
437
438
// Manual inline directive
439
const customInline = new InlineTemplateDirective(
440
`<div class="custom">\${0}</div>`,
441
{ "0": someFactory }
442
);
443
444
const containerTemplate = html`
445
<section>
446
${customInline}
447
</section>
448
`;
449
```
450
451
### Markup Parsing
452
453
Utilities for parsing and processing HTML markup during template compilation.
454
455
```typescript { .api }
456
/**
457
* Markup parsing and processing utilities
458
*/
459
const Markup: {
460
/** Interpolation start marker */
461
interpolationStart: string;
462
463
/** Interpolation end marker */
464
interpolationEnd: string;
465
466
/**
467
* Creates a placeholder for directive interpolation
468
* @param index - The interpolation index
469
*/
470
createPlaceholder(index: number): string;
471
};
472
473
/**
474
* Template parser utilities
475
*/
476
const Parser: {
477
/**
478
* Parses template markup
479
* @param html - The HTML template string
480
* @param factories - The directive factories
481
*/
482
parse(
483
html: string,
484
factories: Record<string, ViewBehaviorFactory>
485
): DocumentFragment;
486
};
487
```
488
489
## Types
490
491
```typescript { .api }
492
/**
493
* Marker interface for capturing template types
494
*/
495
interface CaptureType<TSource, TParent> {}
496
497
/**
498
* Template options for compilation behavior
499
*/
500
interface TemplateOptions {
501
/** Template compilation strategy */
502
strategy?: CompilationStrategy;
503
}
504
505
/**
506
* View behavior factory interface
507
*/
508
interface ViewBehaviorFactory {
509
/** Unique identifier for the factory */
510
id?: string;
511
512
/**
513
* Creates a view behavior
514
* @param targets - The targets for the behavior
515
*/
516
createBehavior(targets: ViewBehaviorTargets): ViewBehavior;
517
}
518
519
/**
520
* Compiled view behavior factory with additional metadata
521
*/
522
interface CompiledViewBehaviorFactory extends ViewBehaviorFactory {
523
/** Target node ID in the compiled template */
524
targetNodeId?: string;
525
526
/** Target tag name */
527
targetTagName?: string | null;
528
}
529
```