or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

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

rendering.mddocs/

0

# Template Rendering

1

2

Core template rendering functionality providing callback-based and streaming output with asynchronous execution and error handling.

3

4

## Capabilities

5

6

### Render Function

7

8

Renders a template with callback-based output, supporting both template names and compiled template functions.

9

10

```javascript { .api }

11

/**

12

* Renders a template with callback-based output

13

* @param nameOrTemplate - Template name (string) or compiled template function

14

* @param context - Data context for template rendering

15

* @param callback - Callback function receiving (error, output)

16

*/

17

function render(

18

nameOrTemplate: string | TemplateFunction,

19

context: any,

20

callback: (err: Error | null, output?: string) => void

21

): void;

22

```

23

24

**Usage Examples:**

25

26

```javascript

27

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

28

29

// Register a template first

30

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

31

dust.loadSource(compiled);

32

33

// Render by name

34

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

35

if (err) throw err;

36

console.log(output); // "Hello Alice!"

37

});

38

39

// Render with compiled function directly

40

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

41

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

42

if (err) throw err;

43

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

44

});

45

46

// Complex context data

47

dust.render('greeting', {

48

name: 'Charlie',

49

items: ['apple', 'banana'],

50

user: { active: true, role: 'admin' }

51

}, (err, output) => {

52

if (err) throw err;

53

console.log(output);

54

});

55

```

56

57

### Stream Function

58

59

Returns a readable stream for template output, enabling streaming responses and real-time data processing.

60

61

```javascript { .api }

62

/**

63

* Returns a readable stream for template output

64

* @param nameOrTemplate - Template name (string) or compiled template function

65

* @param context - Data context for template rendering

66

* @returns DustStream instance with event emitter interface

67

*/

68

function stream(

69

nameOrTemplate: string | TemplateFunction,

70

context: any

71

): DustStream;

72

73

interface DustStream {

74

/** Attach data event listener for rendered chunks */

75

on(event: 'data', callback: (chunk: string) => void): DustStream;

76

/** Attach error event listener for rendering errors */

77

on(event: 'error', callback: (error: Error) => void): DustStream;

78

/** Attach end event listener for rendering completion */

79

on(event: 'end', callback: () => void): DustStream;

80

/** Emit events to listeners */

81

emit(type: string, data?: any): boolean;

82

/** Pipe stream to writable stream */

83

pipe(writable: any): any;

84

}

85

```

86

87

**Usage Examples:**

88

89

```javascript

90

// Stream to stdout

91

dust.stream('greeting', { name: 'David' })

92

.on('data', chunk => process.stdout.write(chunk))

93

.on('end', () => console.log('\n-- Done --'))

94

.on('error', err => console.error('Error:', err));

95

96

// Pipe to HTTP response

97

app.get('/template', (req, res) => {

98

res.setHeader('Content-Type', 'text/html');

99

dust.stream('page', { user: req.user })

100

.pipe(res);

101

});

102

103

// Collect streamed data

104

let result = '';

105

dust.stream('greeting', { name: 'Eva' })

106

.on('data', chunk => result += chunk)

107

.on('end', () => {

108

console.log('Complete output:', result);

109

});

110

```

111

112

### Template Registration Functions

113

114

Functions for registering templates in the cache and loading compiled template source.

115

116

```javascript { .api }

117

/**

118

* Registers a compiled template in the cache

119

* @param name - Template name for later reference

120

* @param compiledTemplate - Compiled template function

121

*/

122

function register(name: string, compiledTemplate: TemplateFunction): void;

123

124

/**

125

* Loads and executes compiled template source code

126

* @param source - String of compiled JavaScript template code

127

* @returns Template function

128

*/

129

function loadSource(source: string): TemplateFunction;

130

```

131

132

**Usage Examples:**

133

134

```javascript

135

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

136

137

// Manual template registration

138

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

139

dust.register('manual-greeting', templateFn);

140

141

// Load compiled source

142

const compiledSource = dust.compile('Goodbye {name}!', 'farewell');

143

const loadedTemplate = dust.loadSource(compiledSource);

144

145

// Templates are now available by name

146

dust.render('manual-greeting', { name: 'Grace' }, console.log);

147

dust.render('farewell', { name: 'Henry' }, console.log);

148

```

149

150

### Chunk Methods for Advanced Rendering

151

152

Low-level chunk methods for custom template logic and rendering operations.

153

154

```javascript { .api }

155

/**

156

* Core chunk methods for template rendering control

157

*/

158

interface ChunkMethods {

159

/** Map over chunk with callback function */

160

map(callback: (chunk: Chunk) => any): Chunk;

161

162

/** Apply output transformation */

163

tap(tap: Function): Chunk;

164

untap(): Chunk;

165

166

/** Render variable reference with filters */

167

reference(elem: any, context: Context, auto?: string, filters?: string[]): Chunk;

168

169

/** Render template section (loops, conditionals) */

170

section(elem: any, context: Context, bodies: Bodies, params?: Params): Chunk;

171

172

/** Conditional rendering - exists */

173

exists(elem: any, context: Context, bodies: Bodies): Chunk;

174

175

/** Conditional rendering - not exists */

176

notexists(elem: any, context: Context, bodies: Bodies): Chunk;

177

178

/** Render template block */

179

block(elem: Function, context: Context, bodies: Bodies): Chunk;

180

181

/** Render partial template */

182

partial(elem: string | Function, context: Context, partialContext?: Context, params?: Params): Chunk;

183

184

/** Call helper function */

185

helper(name: string, context: Context, bodies: Bodies, params?: Params, auto?: string): Chunk;

186

187

/** Handle promise/thenable objects */

188

await(thenable: any, context: Context, bodies: Bodies, auto?: string, filters?: string[]): Chunk;

189

190

/** Handle stream objects */

191

stream(stream: any, context: Context, bodies: Bodies, auto?: string, filters?: string[]): Chunk;

192

193

/** Capture template output */

194

capture(body: Function, context: Context, callback: (output: string, chunk: Chunk) => any): Chunk;

195

196

/** Set error state */

197

setError(err: Error): Chunk;

198

}

199

```

200

201

### Custom Template Loader

202

203

Optional custom template loading function for dynamic template resolution.

204

205

```javascript { .api }

206

/**

207

* Custom template loader function (optional)

208

* Called when template not found in cache

209

*/

210

dust.onLoad?: (

211

name: string,

212

callback: (err: Error | null, template?: string | TemplateFunction) => void

213

) => void;

214

215

// Alternative signature with options

216

dust.onLoad?: (

217

name: string,

218

options: any,

219

callback: (err: Error | null, template?: string | TemplateFunction) => void

220

) => void;

221

```

222

223

**Usage Examples:**

224

225

```javascript

226

// File-based template loader

227

const fs = require('fs');

228

const path = require('path');

229

230

dust.onLoad = (name, callback) => {

231

const templatePath = path.join('./templates', name + '.dust');

232

fs.readFile(templatePath, 'utf8', (err, source) => {

233

if (err) return callback(err);

234

235

try {

236

const compiled = dust.compile(source, name);

237

callback(null, compiled);

238

} catch (compileErr) {

239

callback(compileErr);

240

}

241

});

242

};

243

244

// Now templates load automatically from filesystem

245

dust.render('user-profile', { user: userData }, (err, output) => {

246

// Will automatically load ./templates/user-profile.dust

247

console.log(output);

248

});

249

250

// HTTP-based template loader

251

dust.onLoad = (name, callback) => {

252

const templateUrl = `https://templates.example.com/${name}.dust`;

253

fetch(templateUrl)

254

.then(response => response.text())

255

.then(source => {

256

const compiled = dust.compile(source, name);

257

callback(null, compiled);

258

})

259

.catch(callback);

260

};

261

```

262

263

## Template Cache

264

265

```javascript { .api }

266

/**

267

* Template cache storage

268

* Keys: Template names, Values: Compiled template functions

269

*/

270

const cache: { [templateName: string]: TemplateFunction };

271

```

272

273

**Usage Examples:**

274

275

```javascript

276

// Check if template is cached

277

if (dust.cache['my-template']) {

278

console.log('Template is cached');

279

}

280

281

// Clear specific template from cache

282

delete dust.cache['old-template'];

283

284

// Clear all templates from cache

285

dust.cache = {};

286

287

// List all cached templates

288

console.log('Cached templates:', Object.keys(dust.cache));

289

```

290

291

## Error Handling

292

293

All rendering functions handle errors through callbacks or stream error events:

294

295

```javascript

296

// Callback error handling

297

dust.render('template-name', context, (err, output) => {

298

if (err) {

299

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

300

console.error('Stack:', err.stack);

301

} else {

302

console.log('Success:', output);

303

}

304

});

305

306

// Stream error handling

307

dust.stream('template-name', context)

308

.on('error', err => {

309

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

310

})

311

.on('data', chunk => console.log(chunk))

312

.on('end', () => console.log('Complete'));

313

```

314

315

Common error types:

316

- **Template not found**: When template name is not registered and no `onLoad` handler

317

- **Syntax errors**: When template source contains invalid Dust syntax

318

- **Context errors**: When template references undefined variables (depending on configuration)

319

- **Helper errors**: When helper functions throw exceptions during execution