or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cli.mdcompilation.mdcontext.mdfilters.mdhelpers.mdindex.mdparsing.mdrendering.md

compilation.mddocs/

0

# Template Compilation

1

2

Template compilation system that converts Dust template syntax into executable JavaScript functions with optimization and caching support.

3

4

## Capabilities

5

6

### Compile Function

7

8

Compiles template source code into executable JavaScript string that can be loaded and executed.

9

10

```javascript { .api }

11

/**

12

* Compiles template source to executable JavaScript string

13

* @param source - Dust template source code

14

* @param name - Optional template name for registration and error reporting

15

* @returns String of compiled JavaScript code

16

* @throws SyntaxError with location information for invalid template syntax

17

*/

18

function compile(source: string, name?: string): string;

19

```

20

21

**Usage Examples:**

22

23

```javascript

24

const dust = require('dustjs-linkedin');

25

26

// Basic template compilation

27

const source = 'Hello {name}! Welcome to {site}.';

28

const compiled = dust.compile(source, 'greeting');

29

console.log(compiled);

30

// Output: JavaScript function string

31

32

// Load and use compiled template

33

dust.loadSource(compiled);

34

dust.render('greeting', { name: 'Alice', site: 'My Site' }, (err, output) => {

35

console.log(output); // "Hello Alice! Welcome to My Site."

36

});

37

38

// Complex template with sections and conditionals

39

const complexSource = `

40

{#users}

41

<div class="user {?active}active{/active}">

42

<h3>{name}</h3>

43

{#email}<p>Email: {email}</p>{/email}

44

{^email}<p>No email provided</p>{/email}

45

</div>

46

{/users}

47

{^users}

48

<p>No users found</p>

49

{/users}

50

`;

51

52

try {

53

const compiledComplex = dust.compile(complexSource, 'user-list');

54

dust.loadSource(compiledComplex);

55

} catch (err) {

56

console.error('Compilation error:', err.message);

57

console.error('Location:', err.location);

58

}

59

```

60

61

### Compile Function (Direct Executable)

62

63

Compiles template source and returns an immediately executable template function.

64

65

```javascript { .api }

66

/**

67

* Compiles template and returns executable function

68

* @param source - Dust template source code

69

* @param name - Optional template name

70

* @returns Executable template function

71

* @throws SyntaxError with location information for invalid template syntax

72

*/

73

function compileFn(source: string, name?: string): TemplateFunction;

74

```

75

76

**Usage Examples:**

77

78

```javascript

79

// Compile to function directly

80

const templateFn = dust.compileFn('Goodbye {name}!', 'farewell');

81

82

// Use template function directly

83

dust.render(templateFn, { name: 'Bob' }, (err, output) => {

84

console.log(output); // "Goodbye Bob!"

85

});

86

87

// Template function can be registered manually

88

dust.register('my-farewell', templateFn);

89

dust.render('my-farewell', { name: 'Charlie' }, console.log);

90

91

// Template functions have special properties

92

console.log(templateFn.__dustBody); // true

93

console.log(templateFn.templateName); // 'farewell' (if provided)

94

```

95

96

### Compiler Object

97

98

Access to the complete compiler instance with advanced compilation methods and AST manipulation.

99

100

```javascript { .api }

101

/**

102

* Complete compiler instance with all compilation methods

103

*/

104

const compiler: {

105

compile(source: string, name?: string): string;

106

filterNode(context: any, node: ASTNode): ASTNode;

107

optimizers: OptimizerMap;

108

pragmas: PragmaMap;

109

compileNode(context: any, node: ASTNode): string;

110

nodes: NodeHandlerMap;

111

};

112

113

interface OptimizerMap {

114

body: (context: any, node: ASTNode) => ASTNode;

115

buffer: (context: any, node: ASTNode) => ASTNode;

116

format: (context: any, node: ASTNode) => ASTNode;

117

reference: (context: any, node: ASTNode) => ASTNode;

118

section: (context: any, node: ASTNode) => ASTNode;

119

exists: (context: any, node: ASTNode) => ASTNode;

120

notexists: (context: any, node: ASTNode) => ASTNode;

121

block: (context: any, node: ASTNode) => ASTNode;

122

partial: (context: any, node: ASTNode) => ASTNode;

123

helper: (context: any, node: ASTNode) => ASTNode;

124

[key: string]: (context: any, node: ASTNode) => ASTNode;

125

}

126

127

interface NodeHandlerMap {

128

body: (context: any, node: ASTNode) => string;

129

buffer: (context: any, node: ASTNode) => string;

130

format: (context: any, node: ASTNode) => string;

131

reference: (context: any, node: ASTNode) => string;

132

section: (context: any, node: ASTNode) => string;

133

exists: (context: any, node: ASTNode) => string;

134

notexists: (context: any, node: ASTNode) => string;

135

block: (context: any, node: ASTNode) => string;

136

partial: (context: any, node: ASTNode) => string;

137

helper: (context: any, node: ASTNode) => string;

138

[key: string]: (context: any, node: ASTNode) => string;

139

}

140

141

interface PragmaMap {

142

[pragmaName: string]: (compiler: any, context: any, bodies: any, params: any) => any;

143

}

144

```

145

146

**Usage Examples:**

147

148

```javascript

149

// Direct compiler access

150

const ast = dust.parse('Hello {name}!');

151

const optimizedAst = dust.compiler.filterNode({}, ast);

152

const compiledCode = dust.compiler.compileNode({}, optimizedAst);

153

154

// Custom node optimization

155

const customOptimizer = (context, node) => {

156

// Custom AST transformation logic

157

return node;

158

};

159

160

// Extend compiler with custom optimizer

161

dust.compiler.optimizers.customType = customOptimizer;

162

```

163

164

### Deprecated Compiler APIs

165

166

These APIs were moved to `dust.compiler` namespace in version 2.8.0 but remain available for backward compatibility.

167

168

```javascript { .api }

169

// Deprecated - use dust.compiler.filterNode instead

170

function filterNode(context: any, node: ASTNode): ASTNode;

171

172

// Deprecated - use dust.compiler.optimizers instead

173

const optimizers: OptimizerMap;

174

175

// Deprecated - use dust.compiler.pragmas instead

176

const pragmas: PragmaMap;

177

178

// Deprecated - use dust.compiler.compileNode instead

179

function compileNode(context: any, node: ASTNode): string;

180

181

// Deprecated - use dust.compiler.nodes instead

182

const nodes: NodeHandlerMap;

183

```

184

185

### Template Function Interface

186

187

Properties and behavior of compiled template functions.

188

189

```javascript { .api }

190

interface TemplateFunction {

191

/** Main template execution function */

192

(chunk: Chunk, context: Context): Chunk;

193

194

/** Always true for template functions */

195

__dustBody: true;

196

197

/** Template name when registered */

198

templateName?: string;

199

}

200

```

201

202

**Usage Examples:**

203

204

```javascript

205

const templateFn = dust.compileFn('Hello {name}!', 'greeting');

206

207

// Check if function is a template

208

console.log(templateFn.__dustBody); // true

209

console.log(dust.isTemplateFn(templateFn)); // true

210

211

// Template name property

212

console.log(templateFn.templateName); // 'greeting'

213

214

// Templates registered in cache get their name set

215

dust.register('my-template', templateFn);

216

console.log(dust.cache['my-template'].templateName); // 'my-template'

217

```

218

219

## Compilation Configuration

220

221

Template compilation behavior can be controlled through global configuration:

222

223

```javascript

224

// Whitespace preservation

225

dust.config.whitespace = true; // Preserve whitespace in templates

226

227

// AMD module generation

228

dust.config.amd = true; // Generate AMD-compatible modules

229

230

// CommonJS module generation

231

dust.config.cjs = true; // Generate CommonJS-compatible modules

232

```

233

234

## Error Handling

235

236

Compilation errors include detailed location information for debugging:

237

238

```javascript

239

try {

240

const compiled = dust.compile('{invalid syntax}', 'test-template');

241

} catch (err) {

242

console.log(err.name); // 'SyntaxError'

243

console.log(err.message); // Detailed error message

244

console.log(err.location); // Location object with start/end positions

245

246

// Location includes: { start: { offset, line, column }, end: { offset, line, column } }

247

if (err.location) {

248

console.log(`Error at line ${err.location.start.line}, column ${err.location.start.column}`);

249

}

250

}

251

252

// Template name is included in error messages for debugging

253

try {

254

const compiled = dust.compile('{#unclosed', 'my-template');

255

} catch (err) {

256

console.log(err.message); // Includes '[my-template:1:10]' location info

257

}

258

```

259

260

## Advanced Features

261

262

### Custom AST Processing

263

264

Access to Abstract Syntax Tree for advanced template manipulation:

265

266

```javascript

267

// Parse template to AST

268

const source = 'Hello {name}!';

269

const ast = dust.parse(source);

270

271

// Apply custom AST transformations

272

const transformedAst = dust.compiler.filterNode({}, ast);

273

274

// Compile AST to executable code

275

const code = dust.compiler.compileNode({}, transformedAst);

276

277

// Load the compiled code

278

const templateFn = dust.loadSource(code);

279

```

280

281

### Module Generation

282

283

Generate templates as modules for different environments:

284

285

```javascript

286

// Configure for AMD modules

287

dust.config.amd = true;

288

const amdTemplate = dust.compile('Hello {name}!', 'greeting');

289

// Generated code will be AMD-compatible

290

291

// Configure for CommonJS modules

292

dust.config.cjs = true;

293

const cjsTemplate = dust.compile('Hello {name}!', 'greeting');

294

// Generated code will be CommonJS-compatible

295

296

// Reset to default behavior

297

dust.config.amd = false;

298

dust.config.cjs = false;

299

```