A clean, whitespace-sensitive template language for writing HTML
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
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.
Built-in caching system for compiled templates to improve performance in production applications.
/**
* Template function cache for compiled templates
* Key: template filename, Value: compiled template function
*/
const cache;Usage Examples:
const pug = require('pug');
// Check cache contents
console.log(Object.keys(pug.cache));
// Result: ['./views/layout.pug', './views/user.pug']
// Clear specific template from cache
delete pug.cache['./views/user.pug'];
// Clear entire cache
pug.cache = {};
// Manual cache management
const template = pug.compileFile('./views/product.pug', { cache: true });
// Template is now cached and will be reused
// Check if template is cached
const isCached = './views/product.pug' in pug.cache;
// Force cache refresh
delete pug.cache['./views/product.pug'];
const freshTemplate = pug.compileFile('./views/product.pug', { cache: true });Registry for custom filters that can be used across all templates without passing them in options.
/**
* Global custom filters registry
* Key: filter name, Value: filter function
*/
const filters;Usage Examples:
const pug = require('pug');
// Register global filters
pug.filters.markdown = function(text) {
return require('markdown-it')().render(text);
};
pug.filters.truncate = function(text, length = 100) {
return text.length > length ? text.substring(0, length) + '...' : text;
};
pug.filters.currency = function(amount) {
return '$' + parseFloat(amount).toFixed(2);
};
// Use in templates without passing in options
const html = pug.render(`
div
h1: :markdown # My Title
p: :truncate This is a very long description that will be truncated
span: :currency 19.99
`);
// Check registered filters
console.log(Object.keys(pug.filters));
// Result: ['markdown', 'truncate', 'currency']
// Remove global filter
delete pug.filters.markdown;Direct access to Pug runtime functions for advanced template manipulation and custom processing.
/**
* Pug runtime helpers for template execution
* Contains utility functions used by compiled templates
*/
const runtime;Usage Examples:
const pug = require('pug');
// Access runtime functions
console.log(Object.keys(pug.runtime));
// Result: ['merge', 'classes', 'style', 'attr', 'escape', 'rethrow']
// Use runtime functions directly
const escaped = pug.runtime.escape('<script>alert("xss")</script>');
// Result: '<script>alert("xss")</script>'
const merged = pug.runtime.merge({ a: 1 }, { b: 2 });
// Result: { a: 1, b: 2 }
const classes = pug.runtime.classes(['active', { hidden: false, visible: true }]);
// Result: 'active visible'
// Custom template function using runtime
function customTemplate(locals) {
const { escape, classes } = pug.runtime;
return `<div class="${classes(locals.cssClasses)}">${escape(locals.content)}</div>`;
}Basic library identification and metadata.
/**
* Library identification name
*/
const name;Usage Examples:
const pug = require('pug');
console.log(pug.name); // 'Pug'
// Feature detection
if (pug.name === 'Pug') {
console.log('Using Pug template engine');
}Environment-Based Caching:
const pug = require('pug');
// Production caching setup
const isProduction = process.env.NODE_ENV === 'production';
function renderTemplate(templatePath, locals) {
return pug.renderFile(templatePath, {
...locals,
cache: isProduction,
compileDebug: !isProduction
});
}
// Development: templates recompiled on each request
// Production: templates cached after first compilation
const html = renderTemplate('./views/dashboard.pug', { user: userData });Custom Cache Management:
const pug = require('pug');
class TemplateCache {
constructor() {
this.cache = new Map();
this.maxSize = 100;
}
get(key) {
return this.cache.get(key);
}
set(key, value) {
if (this.cache.size >= this.maxSize) {
const firstKey = this.cache.keys().next().value;
this.cache.delete(firstKey);
}
this.cache.set(key, value);
}
clear() {
this.cache.clear();
}
}
const templateCache = new TemplateCache();
// Replace Pug's cache with custom implementation
Object.defineProperty(pug, 'cache', {
get: () => templateCache,
set: () => {} // Prevent replacement
});Cache Warming:
const pug = require('pug');
const fs = require('fs');
const path = require('path');
// Warm cache on application startup
function warmTemplateCache(templateDir) {
const templates = fs.readdirSync(templateDir)
.filter(file => file.endsWith('.pug'))
.map(file => path.join(templateDir, file));
templates.forEach(templatePath => {
pug.compileFile(templatePath, { cache: true });
console.log(`Cached template: ${templatePath}`);
});
console.log(`Warmed ${templates.length} templates`);
}
// Call during app initialization
warmTemplateCache('./views');Advanced Filter Registration:
const pug = require('pug');
// Register multiple filters at once
Object.assign(pug.filters, {
// Date formatting filter
date: function(date, format = 'short') {
const d = new Date(date);
const formats = {
short: d.toLocaleDateString(),
long: d.toLocaleDateString('en-US', {
year: 'numeric', month: 'long', day: 'numeric'
}),
iso: d.toISOString()
};
return formats[format] || formats.short;
},
// JSON pretty print filter
json: function(obj, indent = 2) {
return JSON.stringify(obj, null, indent);
},
// Base64 encoding filter
base64: function(text) {
return Buffer.from(text).toString('base64');
},
// URL encoding filter
urlencode: function(text) {
return encodeURIComponent(text);
}
});
// Use filters in templates
const html = pug.render(`
div
p: :date #{new Date()}
pre: :json #{data}
a(href="/search?q=" + (:urlencode query)) Search
`, {
data: { users: ['Alice', 'Bob'] },
query: 'hello world'
});Filter with Options:
pug.filters.highlight = function(text, options = {}) {
const { language = 'javascript', theme = 'default' } = options;
// Assume highlight.js integration
return hljs.highlight(language, text).value;
};
// Usage in template with filter options
const html = pug.render(`
pre: :highlight(language='python') print("Hello World")
`, {}, {
filterOptions: {
highlight: { theme: 'monokai' }
}
});Cache Statistics:
const pug = require('pug');
function getCacheStats() {
const cacheKeys = Object.keys(pug.cache);
return {
size: cacheKeys.length,
templates: cacheKeys,
memoryUsage: process.memoryUsage().heapUsed
};
}
// Monitor cache performance
setInterval(() => {
const stats = getCacheStats();
console.log(`Cache size: ${stats.size} templates`);
if (stats.size > 50) {
console.warn('Template cache is growing large, consider cleanup');
}
}, 60000); // Check every minuteTemplate Compilation Timing:
const originalCompile = pug.compile;
pug.compile = function(str, options) {
const start = Date.now();
const template = originalCompile.call(this, str, options);
const duration = Date.now() - start;
console.log(`Template compilation took ${duration}ms`);
if (duration > 100) {
console.warn('Slow template compilation detected');
}
return template;
};Pug provides automatic compilation support for .pug files when required directly in Node.js applications.
/**
* Register .pug extension with Node.js require() system
* Enables direct require() of .pug files as compiled templates
*/
require('pug/register');Usage Examples:
// Enable .pug file require() support
require('pug/register');
// Now you can require .pug files directly
const template = require('./views/user-card.pug');
// Use the compiled template
const html = template({
user: {
name: 'Alice',
email: 'alice@example.com'
}
});
console.log(html); // Rendered HTML outputAdvanced Registration Usage:
// Register in application bootstrap
require('pug/register');
// Dynamic template loading
function loadTemplate(name) {
return require(`./templates/${name}.pug`);
}
const headerTemplate = loadTemplate('header');
const footerTemplate = loadTemplate('footer');
// Use templates
const headerHtml = headerTemplate({ title: 'My App' });
const footerHtml = footerTemplate({ year: 2023 });Build System Integration:
// webpack.config.js - use with webpack
module.exports = {
entry: './src/app.js',
module: {
rules: [
{
test: /\.pug$/,
use: [
{
loader: 'apply-loader'
},
{
loader: 'pug-loader'
}
]
}
]
}
};
// In your application code
require('pug/register');
const template = require('./template.pug');Configuration errors typically occur with:
// Filter error handling
try {
pug.filters.badFilter = "not a function";
pug.render('p: :badFilter Hello');
} catch (err) {
console.error('Filter error:', err.message);
}
// Cache error handling
try {
pug.cache = null; // Invalid cache assignment
} catch (err) {
console.error('Cache error:', err.message);
}
// Runtime function errors
try {
const result = pug.runtime.classes(null); // Invalid input
} catch (err) {
console.error('Runtime error:', err.message);
}
// Registration error handling
try {
require('pug/register');
const template = require('./non-existent-template.pug');
} catch (err) {
console.error('Template require error:', err.message);
}Install with Tessl CLI
npx tessl i tessl/npm-pug