or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

built-in-directives.mdcore-templates.mdcustom-directives.mdindex.mdstatic-templates.md
tile.json

core-templates.mddocs/

0

# Core Template System

1

2

Essential template creation and rendering functionality for building dynamic HTML interfaces with efficient incremental DOM updates.

3

4

## Capabilities

5

6

### HTML Template Function

7

8

Creates HTML templates from template literals with embedded expressions.

9

10

```typescript { .api }

11

/**

12

* Interprets a template literal as an HTML template that can efficiently

13

* render to and update a container.

14

* @param strings - Template strings array

15

* @param values - Template expression values

16

* @returns Template result for rendering

17

*/

18

function html(strings: TemplateStringsArray, ...values: unknown[]): TemplateResult;

19

```

20

21

**Usage Examples:**

22

23

```typescript

24

import { html } from 'lit-html';

25

26

// Simple template

27

const greeting = html`<h1>Hello World!</h1>`;

28

29

// Template with expressions

30

const userCard = (name: string, age: number) => html`

31

<div class="card">

32

<h2>${name}</h2>

33

<p>Age: ${age}</p>

34

</div>

35

`;

36

37

// Conditional content with nothing

38

const maybeButton = (showButton: boolean) => html`

39

${showButton ? html`<button>Click me</button>` : nothing}

40

`;

41

```

42

43

### SVG Template Function

44

45

Creates SVG templates for vector graphics content within HTML templates.

46

47

```typescript { .api }

48

/**

49

* Interprets a template literal as an SVG fragment that can efficiently render

50

* to and update a container.

51

* @param strings - Template strings array

52

* @param values - Template expression values

53

* @returns SVG template result for rendering

54

*/

55

function svg(strings: TemplateStringsArray, ...values: unknown[]): SVGTemplateResult;

56

```

57

58

**Usage Examples:**

59

60

```typescript

61

import { html, svg } from 'lit-html';

62

63

// SVG fragment for use inside HTML

64

const icon = (size: number) => svg`

65

<circle cx="50" cy="50" r="${size}" fill="blue"/>

66

<text x="50" y="55" text-anchor="middle">Icon</text>

67

`;

68

69

// Use SVG in HTML template

70

const iconButton = html`

71

<button>

72

<svg viewBox="0 0 100 100" width="24" height="24">

73

${icon(40)}

74

</svg>

75

Click me

76

</button>

77

`;

78

```

79

80

### MathML Template Function

81

82

Creates MathML templates for mathematical notation within HTML templates.

83

84

```typescript { .api }

85

/**

86

* Interprets a template literal as MathML fragment that can efficiently render

87

* to and update a container.

88

* @param strings - Template strings array

89

* @param values - Template expression values

90

* @returns MathML template result for rendering

91

*/

92

function mathml(strings: TemplateStringsArray, ...values: unknown[]): MathMLTemplateResult;

93

```

94

95

**Usage Examples:**

96

97

```typescript

98

import { html, mathml } from 'lit-html';

99

100

// Mathematical equation

101

const quadraticFormula = mathml`

102

<mrow>

103

<mi>x</mi>

104

<mo>=</mo>

105

<mfrac>

106

<mrow>

107

<mo>-</mo>

108

<mi>b</mi>

109

<mo>±</mo>

110

<msqrt>

111

<mrow>

112

<msup><mi>b</mi><mn>2</mn></msup>

113

<mo>-</mo>

114

<mn>4</mn>

115

<mi>a</mi>

116

<mi>c</mi>

117

</mrow>

118

</msqrt>

119

</mrow>

120

<mrow>

121

<mn>2</mn>

122

<mi>a</mi>

123

</mrow>

124

</mfrac>

125

</mrow>

126

`;

127

128

// Use MathML in HTML

129

const mathExample = html`

130

<div>

131

<h3>Quadratic Formula:</h3>

132

<math>

133

${quadraticFormula}

134

</math>

135

</div>

136

`;

137

```

138

139

### Render Function

140

141

Renders template results to DOM containers with efficient incremental updates.

142

143

```typescript { .api }

144

/**

145

* Renders a value, usually a lit-html TemplateResult, to the container.

146

* @param value - Any renderable value, typically a TemplateResult

147

* @param container - DOM container to render to

148

* @param options - Optional rendering configuration

149

* @returns RootPart for managing the rendered content

150

*/

151

function render(

152

value: unknown,

153

container: HTMLElement | DocumentFragment,

154

options?: RenderOptions

155

): RootPart;

156

```

157

158

**Usage Examples:**

159

160

```typescript

161

import { html, render } from 'lit-html';

162

163

// Basic rendering

164

const template = html`<h1>Hello World</h1>`;

165

render(template, document.body);

166

167

// Rendering with options

168

render(template, document.body, {

169

host: myComponent,

170

renderBefore: existingElement

171

});

172

173

// Managing the returned RootPart

174

const part = render(template, container);

175

part.setConnected(false); // Disconnect async directives

176

```

177

178

### Sentinel Values

179

180

Special values for controlling template rendering behavior.

181

182

```typescript { .api }

183

/**

184

* A sentinel value that signals a ChildPart to fully clear its content.

185

* Prefer using `nothing` over other falsy values for consistent behavior.

186

*/

187

const nothing: unique symbol;

188

189

/**

190

* A sentinel value that signals that a value was handled by a directive and

191

* should not be written to the DOM.

192

*/

193

const noChange: unique symbol;

194

```

195

196

**Usage Examples:**

197

198

```typescript

199

import { html, nothing, noChange } from 'lit-html';

200

201

// Using nothing for conditional content

202

const conditionalContent = (show: boolean) => html`

203

<div>

204

${show ? html`<p>Visible content</p>` : nothing}

205

</div>

206

`;

207

208

// Using noChange in custom directives

209

class MyDirective extends Directive {

210

render(value: string) {

211

if (value === this.previousValue) {

212

return noChange; // Skip update

213

}

214

this.previousValue = value;

215

return value;

216

}

217

}

218

```

219

220

## Types

221

222

```typescript { .api }

223

interface TemplateResult<T extends ResultType = ResultType> {

224

readonly strings: TemplateStringsArray;

225

readonly values: unknown[];

226

}

227

228

type HTMLTemplateResult = TemplateResult<typeof HTML_RESULT>;

229

type SVGTemplateResult = TemplateResult<typeof SVG_RESULT>;

230

type MathMLTemplateResult = TemplateResult<typeof MATHML_RESULT>;

231

232

interface RenderOptions {

233

/** An object to use as the `this` value for event listeners */

234

host?: object;

235

/** A DOM node before which to render content in the container */

236

renderBefore?: ChildNode | null;

237

/** Node used for cloning the template (controls ownerDocument) */

238

creationScope?: { importNode(node: Node, deep?: boolean): Node };

239

/** Initial connected state for the top-level part being rendered */

240

isConnected?: boolean;

241

}

242

243

interface RootPart extends ChildPart {

244

/** Sets the connection state for AsyncDirectives contained within this root */

245

setConnected(isConnected: boolean): void;

246

}

247

```

248

249

### Server Detection

250

251

Utility for detecting server environments in universal/isomorphic applications.

252

253

```typescript { .api }

254

/**

255

* A boolean that will be `true` in server environments like Node, and `false`

256

* in browser environments. Note that your server environment or toolchain must

257

* support the "node" export condition for this to be `true`.

258

*/

259

const isServer: boolean;

260

```

261

262

**Usage Examples:**

263

264

```typescript

265

import { isServer } from 'lit-html/is-server.js';

266

267

// Conditional behavior based on environment

268

const template = html`

269

<div>

270

${isServer

271

? html`<p>Rendered on server</p>`

272

: html`<p>Rendered in browser</p>`

273

}

274

</div>

275

`;

276

277

// Skip browser-specific APIs on server

278

if (!isServer) {

279

// Safe to use browser APIs

280

element.focus();

281

}

282

```

283

284

### Security APIs

285

286

Security-related functions for controlling value sanitization and DOM safety.

287

288

```typescript { .api }

289

/**

290

* A function which can sanitize values that will be written to a specific kind

291

* of DOM sink (property or attribute).

292

* @param value - The value to sanitize

293

* @returns The sanitized value to write to the DOM

294

*/

295

type ValueSanitizer = (value: unknown) => unknown;

296

297

/**

298

* Factory function that creates a sanitizer for a specific DOM context.

299

* @param node - The HTML node that is being written to

300

* @param name - The name of an attribute or property

301

* @param type - Whether the write is to a property or attribute

302

* @returns A function that will sanitize values for this context

303

*/

304

type SanitizerFactory = (

305

node: Node,

306

name: string,

307

type: 'property' | 'attribute'

308

) => ValueSanitizer;

309

310

/**

311

* Sets the global sanitizer factory for controlling value sanitization.

312

* Can only be called once - subsequent calls will throw an error.

313

* @param sanitizerFactory - Factory function for creating sanitizers

314

*/

315

render.setSanitizer = (sanitizerFactory: SanitizerFactory) => void;

316

317

/**

318

* Creates a sanitizer for a specific DOM context using the current global factory.

319

* @param node - The HTML node context

320

* @param name - The attribute or property name

321

* @param type - Whether this is for a property or attribute

322

* @returns ValueSanitizer function for this context

323

*/

324

render.createSanitizer = (

325

node: Node,

326

name: string,

327

type: 'property' | 'attribute'

328

) => ValueSanitizer;

329

```

330

331

**Usage Examples:**

332

333

```typescript

334

import { render } from 'lit-html';

335

336

// Set up a custom sanitizer factory

337

render.setSanitizer((node, name, type) => {

338

if (type === 'attribute' && name === 'src') {

339

// Custom sanitization for src attributes

340

return (value) => {

341

const url = String(value);

342

// Only allow https URLs

343

return url.startsWith('https://') ? url : '';

344

};

345

}

346

347

if (type === 'property' && name === 'innerHTML') {

348

// Sanitize innerHTML property

349

return (value) => {

350

// Remove script tags (basic example)

351

return String(value).replace(/<script[^>]*>.*?<\/script>/gi, '');

352

};

353

}

354

355

// Default: no sanitization

356

return (value) => value;

357

});

358

359

// Create a sanitizer for a specific context

360

const imgElement = document.createElement('img');

361

const srcSanitizer = render.createSanitizer(imgElement, 'src', 'attribute');

362

363

// Use the sanitizer

364

const safeUrl = srcSanitizer('https://example.com/image.jpg'); // Allowed

365

const blockedUrl = srcSanitizer('javascript:alert("xss")'); // Blocked

366

367

// Security policies example

368

render.setSanitizer((node, name, type) => {

369

// High-risk attributes that need sanitization

370

const highRiskAttrs = ['src', 'href', 'action', 'formaction'];

371

372

if (type === 'attribute' && highRiskAttrs.includes(name)) {

373

return (value) => {

374

const str = String(value);

375

// Block javascript: and data: URLs

376

if (str.match(/^(javascript|data):/i)) {

377

console.warn(`Blocked potentially unsafe ${name}: ${str}`);

378

return '';

379

}

380

return str;

381

};

382

}

383

384

return (value) => value;

385

});

386

```