or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

client-compilation.mdcompilation.mdconfiguration.mdexpress-integration.mdindex.mdrendering.md

configuration.mddocs/

0

# Configuration and Caching

1

2

Template caching, global filters, and runtime configuration for optimizing performance and extending Pug functionality. These features enable fine-tuned control over template processing and execution.

3

4

## Capabilities

5

6

### Template Caching

7

8

Built-in caching system for compiled templates to improve performance in production applications.

9

10

```javascript { .api }

11

/**

12

* Template function cache for compiled templates

13

* Key: template filename, Value: compiled template function

14

*/

15

const cache;

16

```

17

18

**Usage Examples:**

19

20

```javascript

21

const pug = require('pug');

22

23

// Check cache contents

24

console.log(Object.keys(pug.cache));

25

// Result: ['./views/layout.pug', './views/user.pug']

26

27

// Clear specific template from cache

28

delete pug.cache['./views/user.pug'];

29

30

// Clear entire cache

31

pug.cache = {};

32

33

// Manual cache management

34

const template = pug.compileFile('./views/product.pug', { cache: true });

35

// Template is now cached and will be reused

36

37

// Check if template is cached

38

const isCached = './views/product.pug' in pug.cache;

39

40

// Force cache refresh

41

delete pug.cache['./views/product.pug'];

42

const freshTemplate = pug.compileFile('./views/product.pug', { cache: true });

43

```

44

45

### Global Filters

46

47

Registry for custom filters that can be used across all templates without passing them in options.

48

49

```javascript { .api }

50

/**

51

* Global custom filters registry

52

* Key: filter name, Value: filter function

53

*/

54

const filters;

55

```

56

57

**Usage Examples:**

58

59

```javascript

60

const pug = require('pug');

61

62

// Register global filters

63

pug.filters.markdown = function(text) {

64

return require('markdown-it')().render(text);

65

};

66

67

pug.filters.truncate = function(text, length = 100) {

68

return text.length > length ? text.substring(0, length) + '...' : text;

69

};

70

71

pug.filters.currency = function(amount) {

72

return '$' + parseFloat(amount).toFixed(2);

73

};

74

75

// Use in templates without passing in options

76

const html = pug.render(`

77

div

78

h1: :markdown # My Title

79

p: :truncate This is a very long description that will be truncated

80

span: :currency 19.99

81

`);

82

83

// Check registered filters

84

console.log(Object.keys(pug.filters));

85

// Result: ['markdown', 'truncate', 'currency']

86

87

// Remove global filter

88

delete pug.filters.markdown;

89

```

90

91

### Runtime Access

92

93

Direct access to Pug runtime functions for advanced template manipulation and custom processing.

94

95

```javascript { .api }

96

/**

97

* Pug runtime helpers for template execution

98

* Contains utility functions used by compiled templates

99

*/

100

const runtime;

101

```

102

103

**Usage Examples:**

104

105

```javascript

106

const pug = require('pug');

107

108

// Access runtime functions

109

console.log(Object.keys(pug.runtime));

110

// Result: ['merge', 'classes', 'style', 'attr', 'escape', 'rethrow']

111

112

// Use runtime functions directly

113

const escaped = pug.runtime.escape('<script>alert("xss")</script>');

114

// Result: '&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;'

115

116

const merged = pug.runtime.merge({ a: 1 }, { b: 2 });

117

// Result: { a: 1, b: 2 }

118

119

const classes = pug.runtime.classes(['active', { hidden: false, visible: true }]);

120

// Result: 'active visible'

121

122

// Custom template function using runtime

123

function customTemplate(locals) {

124

const { escape, classes } = pug.runtime;

125

return `<div class="${classes(locals.cssClasses)}">${escape(locals.content)}</div>`;

126

}

127

```

128

129

### Library Information

130

131

Basic library identification and metadata.

132

133

```javascript { .api }

134

/**

135

* Library identification name

136

*/

137

const name;

138

```

139

140

**Usage Examples:**

141

142

```javascript

143

const pug = require('pug');

144

145

console.log(pug.name); // 'Pug'

146

147

// Feature detection

148

if (pug.name === 'Pug') {

149

console.log('Using Pug template engine');

150

}

151

```

152

153

### Advanced Caching Strategies

154

155

**Environment-Based Caching:**

156

157

```javascript

158

const pug = require('pug');

159

160

// Production caching setup

161

const isProduction = process.env.NODE_ENV === 'production';

162

163

function renderTemplate(templatePath, locals) {

164

return pug.renderFile(templatePath, {

165

...locals,

166

cache: isProduction,

167

compileDebug: !isProduction

168

});

169

}

170

171

// Development: templates recompiled on each request

172

// Production: templates cached after first compilation

173

const html = renderTemplate('./views/dashboard.pug', { user: userData });

174

```

175

176

**Custom Cache Management:**

177

178

```javascript

179

const pug = require('pug');

180

181

class TemplateCache {

182

constructor() {

183

this.cache = new Map();

184

this.maxSize = 100;

185

}

186

187

get(key) {

188

return this.cache.get(key);

189

}

190

191

set(key, value) {

192

if (this.cache.size >= this.maxSize) {

193

const firstKey = this.cache.keys().next().value;

194

this.cache.delete(firstKey);

195

}

196

this.cache.set(key, value);

197

}

198

199

clear() {

200

this.cache.clear();

201

}

202

}

203

204

const templateCache = new TemplateCache();

205

206

// Replace Pug's cache with custom implementation

207

Object.defineProperty(pug, 'cache', {

208

get: () => templateCache,

209

set: () => {} // Prevent replacement

210

});

211

```

212

213

**Cache Warming:**

214

215

```javascript

216

const pug = require('pug');

217

const fs = require('fs');

218

const path = require('path');

219

220

// Warm cache on application startup

221

function warmTemplateCache(templateDir) {

222

const templates = fs.readdirSync(templateDir)

223

.filter(file => file.endsWith('.pug'))

224

.map(file => path.join(templateDir, file));

225

226

templates.forEach(templatePath => {

227

pug.compileFile(templatePath, { cache: true });

228

console.log(`Cached template: ${templatePath}`);

229

});

230

231

console.log(`Warmed ${templates.length} templates`);

232

}

233

234

// Call during app initialization

235

warmTemplateCache('./views');

236

```

237

238

### Filter System

239

240

**Advanced Filter Registration:**

241

242

```javascript

243

const pug = require('pug');

244

245

// Register multiple filters at once

246

Object.assign(pug.filters, {

247

// Date formatting filter

248

date: function(date, format = 'short') {

249

const d = new Date(date);

250

const formats = {

251

short: d.toLocaleDateString(),

252

long: d.toLocaleDateString('en-US', {

253

year: 'numeric', month: 'long', day: 'numeric'

254

}),

255

iso: d.toISOString()

256

};

257

return formats[format] || formats.short;

258

},

259

260

// JSON pretty print filter

261

json: function(obj, indent = 2) {

262

return JSON.stringify(obj, null, indent);

263

},

264

265

// Base64 encoding filter

266

base64: function(text) {

267

return Buffer.from(text).toString('base64');

268

},

269

270

// URL encoding filter

271

urlencode: function(text) {

272

return encodeURIComponent(text);

273

}

274

});

275

276

// Use filters in templates

277

const html = pug.render(`

278

div

279

p: :date #{new Date()}

280

pre: :json #{data}

281

a(href="/search?q=" + (:urlencode query)) Search

282

`, {

283

data: { users: ['Alice', 'Bob'] },

284

query: 'hello world'

285

});

286

```

287

288

**Filter with Options:**

289

290

```javascript

291

pug.filters.highlight = function(text, options = {}) {

292

const { language = 'javascript', theme = 'default' } = options;

293

// Assume highlight.js integration

294

return hljs.highlight(language, text).value;

295

};

296

297

// Usage in template with filter options

298

const html = pug.render(`

299

pre: :highlight(language='python') print("Hello World")

300

`, {}, {

301

filterOptions: {

302

highlight: { theme: 'monokai' }

303

}

304

});

305

```

306

307

### Performance Monitoring

308

309

**Cache Statistics:**

310

311

```javascript

312

const pug = require('pug');

313

314

function getCacheStats() {

315

const cacheKeys = Object.keys(pug.cache);

316

return {

317

size: cacheKeys.length,

318

templates: cacheKeys,

319

memoryUsage: process.memoryUsage().heapUsed

320

};

321

}

322

323

// Monitor cache performance

324

setInterval(() => {

325

const stats = getCacheStats();

326

console.log(`Cache size: ${stats.size} templates`);

327

if (stats.size > 50) {

328

console.warn('Template cache is growing large, consider cleanup');

329

}

330

}, 60000); // Check every minute

331

```

332

333

**Template Compilation Timing:**

334

335

```javascript

336

const originalCompile = pug.compile;

337

338

pug.compile = function(str, options) {

339

const start = Date.now();

340

const template = originalCompile.call(this, str, options);

341

const duration = Date.now() - start;

342

343

console.log(`Template compilation took ${duration}ms`);

344

if (duration > 100) {

345

console.warn('Slow template compilation detected');

346

}

347

348

return template;

349

};

350

```

351

352

### Node.js require() Registration

353

354

Pug provides automatic compilation support for .pug files when required directly in Node.js applications.

355

356

```javascript { .api }

357

/**

358

* Register .pug extension with Node.js require() system

359

* Enables direct require() of .pug files as compiled templates

360

*/

361

require('pug/register');

362

```

363

364

**Usage Examples:**

365

366

```javascript

367

// Enable .pug file require() support

368

require('pug/register');

369

370

// Now you can require .pug files directly

371

const template = require('./views/user-card.pug');

372

373

// Use the compiled template

374

const html = template({

375

user: {

376

name: 'Alice',

377

email: 'alice@example.com'

378

}

379

});

380

381

console.log(html); // Rendered HTML output

382

```

383

384

**Advanced Registration Usage:**

385

386

```javascript

387

// Register in application bootstrap

388

require('pug/register');

389

390

// Dynamic template loading

391

function loadTemplate(name) {

392

return require(`./templates/${name}.pug`);

393

}

394

395

const headerTemplate = loadTemplate('header');

396

const footerTemplate = loadTemplate('footer');

397

398

// Use templates

399

const headerHtml = headerTemplate({ title: 'My App' });

400

const footerHtml = footerTemplate({ year: 2023 });

401

```

402

403

**Build System Integration:**

404

405

```javascript

406

// webpack.config.js - use with webpack

407

module.exports = {

408

entry: './src/app.js',

409

module: {

410

rules: [

411

{

412

test: /\.pug$/,

413

use: [

414

{

415

loader: 'apply-loader'

416

},

417

{

418

loader: 'pug-loader'

419

}

420

]

421

}

422

]

423

}

424

};

425

426

// In your application code

427

require('pug/register');

428

const template = require('./template.pug');

429

```

430

431

### Error Handling

432

433

Configuration errors typically occur with:

434

435

- Invalid filter functions

436

- Cache corruption

437

- Runtime function misuse

438

- Registration conflicts

439

440

```javascript

441

// Filter error handling

442

try {

443

pug.filters.badFilter = "not a function";

444

pug.render('p: :badFilter Hello');

445

} catch (err) {

446

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

447

}

448

449

// Cache error handling

450

try {

451

pug.cache = null; // Invalid cache assignment

452

} catch (err) {

453

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

454

}

455

456

// Runtime function errors

457

try {

458

const result = pug.runtime.classes(null); // Invalid input

459

} catch (err) {

460

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

461

}

462

463

// Registration error handling

464

try {

465

require('pug/register');

466

const template = require('./non-existent-template.pug');

467

} catch (err) {

468

console.error('Template require error:', err.message);

469

}

470

```