CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-pug

A clean, whitespace-sensitive template language for writing HTML

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

rendering.mddocs/

Template Rendering

Direct template-to-HTML conversion for simple use cases and development environments. These functions combine compilation and execution in a single step, making them ideal for one-time rendering or prototyping.

Capabilities

Render Function

Renders a Pug template string directly to HTML without explicitly creating a template function.

/**
 * Render a Pug template string directly to HTML
 * @param str - Pug template source code
 * @param options - Rendering options including locals
 * @param fn - Optional callback for async operation
 * @returns HTML string (sync) or calls callback (async)
 */
function render(str, options, fn);

Usage Examples:

const pug = require('pug');

// Basic rendering
const html = pug.render('p Hello #{name}!', { name: 'World' });
// Result: <p>Hello World!</p>

// With template options
const html2 = pug.render(`
doctype html
html
  head
    title= title
  body
    h1= heading
    if users
      ul
        each user in users
          li= user.name
`, {
  title: 'User List',
  heading: 'All Users',
  users: [
    { name: 'Alice' },
    { name: 'Bob' },
    { name: 'Charlie' }
  ],
  pretty: true
});

// Async rendering with callback
pug.render('p Processing...', {}, function(err, html) {
  if (err) {
    console.error('Rendering error:', err);
  } else {
    console.log('Rendered:', html);
  }
});

Render File Function

Renders a Pug template file directly to HTML.

/**
 * Render a Pug template file directly to HTML
 * @param path - Path to Pug template file 
 * @param options - Rendering options including locals
 * @param fn - Optional callback for async operation
 * @returns HTML string (sync) or calls callback (async)
 */
function renderFile(path, options, fn);

Usage Examples:

const pug = require('pug');

// Render from file
const html = pug.renderFile('./views/user-profile.pug', {
  user: {
    name: 'Alice Smith',
    email: 'alice@example.com',
    avatar: '/images/alice.jpg'
  },
  isLoggedIn: true
});

// With caching for performance
const html2 = pug.renderFile('./views/dashboard.pug', {
  cache: true,
  filename: './views/dashboard.pug', // Required for caching
  user: { name: 'Bob' },
  stats: { posts: 42, followers: 156 }
});

// Async rendering
pug.renderFile('./views/email-template.pug', {
  recipient: 'user@example.com',
  subject: 'Welcome!'
}, function(err, html) {
  if (err) {
    console.error('Template error:', err);
  } else {
    // Send email with rendered HTML
    sendEmail(html);
  }
});

Rendering Options

Rendering functions accept all compilation options plus template locals:

interface RenderingOptions extends CompilationOptions {
  /** Enable template caching (requires filename for file-based rendering) */
  cache?: boolean;
  /** Template variables - any additional properties become template locals */
  [localName: string]: any;
}

Callback Interface

For async operations, callbacks follow the standard Node.js error-first pattern:

/**
 * Callback function for async rendering operations
 * @param err - Error object if rendering failed, null if successful
 * @param html - Rendered HTML string if successful
 */
type RenderCallback = (err: Error | null, html?: string) => void;

Advanced Usage

Template with Includes:

// views/layout.pug
const html = pug.renderFile('./views/page.pug', {
  basedir: './views',
  title: 'My Page',
  content: 'Hello World'
});

// The template can use: include header.pug, include footer.pug

Dynamic Template Selection:

function renderTemplate(templateName, data) {
  const templatePath = `./views/${templateName}.pug`;
  return pug.renderFile(templatePath, {
    ...data,
    basedir: './views',
    cache: process.env.NODE_ENV === 'production'
  });
}

const html = renderTemplate('user-card', { user: userData });

Conditional Rendering:

const html = pug.render(`
div.notification(class=type)
  if type === 'error'
    i.icon-error
  else if type === 'warning'  
    i.icon-warning
  else
    i.icon-info
  p= message
`, {
  type: 'error',
  message: 'Something went wrong!'
});

Loop Rendering:

const html = pug.render(`
table
  thead
    tr
      th Name
      th Email
      th Status
  tbody
    each user in users
      tr(class=user.active ? 'active' : 'inactive')
        td= user.name
        td= user.email
        td= user.active ? 'Active' : 'Inactive'
`, {
  users: [
    { name: 'Alice', email: 'alice@example.com', active: true },
    { name: 'Bob', email: 'bob@example.com', active: false }
  ]
});

Error Handling

Both rendering functions can throw errors or pass errors to callbacks:

// Synchronous error handling
try {
  const html = pug.render('invalid syntax {{}}');
} catch (err) {
  console.error('Rendering failed:', err.message);
}

// Asynchronous error handling
pug.render('p Hello', {}, function(err, html) {
  if (err) {
    console.error('Async rendering failed:', err.message);
    return;
  }
  console.log('Success:', html);
});

// File not found errors
try {
  const html = pug.renderFile('./non-existent.pug', {});
} catch (err) {
  console.error('File error:', err.code); // ENOENT
}

Performance Considerations

  • Use renderFile with caching for production applications
  • Use render for dynamic templates or development
  • Consider compile + template function for templates rendered multiple times
  • Set compileDebug: false in production for better performance
// Production rendering setup
const isProduction = process.env.NODE_ENV === 'production';

const html = pug.renderFile('./views/app.pug', {
  cache: isProduction,
  compileDebug: !isProduction,
  pretty: !isProduction,
  // ... template data
});

Install with Tessl CLI

npx tessl i tessl/npm-pug

docs

client-compilation.md

compilation.md

configuration.md

express-integration.md

index.md

rendering.md

tile.json