CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-dustjs-helpers

Context helpers that extend the core Dust.js templating system with conditional logic, mathematical operations, and iteration utilities.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

index.mddocs/

Dustjs Helpers

Dustjs Helpers provides a comprehensive collection of context helpers that extend the core Dust.js templating system functionality. It includes essential template helpers for conditional logic (@select, @when), iteration (@size), mathematical operations (@math), and other common templating tasks that fulfill the most frequently encountered use cases in Dust templating.

Package Information

  • Package Name: dustjs-helpers
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install dustjs-helpers

Core Imports

CommonJS (Node.js) - Primary usage pattern:

const dustjsHelpers = require('dustjs-helpers');
// Auto-registers all helpers with the dust instance provided by dustjs-linkedin

Manual registration with existing dust instance:

const dust = require('dustjs-linkedin');
const dustjsHelpers = require('dustjs-helpers');
dustjsHelpers.registerWith(dust);

AMD module (RequireJS):

define(['dust.core'], function(dust) {
  // When using AMD, specify dust.core as dependency
  define(['dustjs-helpers'], function(helpers) {
    // helpers are automatically registered with dust
    return helpers;
  });
});

Browser (Script tag):

<script src="dust.js"></script>
<script src="dustjs-helpers.js"></script>
<!-- Helpers are automatically registered with window.dust -->

Browser (UMD pattern):

(function() {
  // If dust is available globally, helpers register automatically
  if (typeof dust !== 'undefined') {
    // Helpers are now available on dust.helpers
    dust.render(template, context, callback);
  }
})();

Basic Usage

All helpers are used within Dust.js templates using the {@helperName} syntax:

// Template compilation and rendering
const dust = require('dustjs-linkedin');
require('dustjs-helpers'); // Auto-registers helpers

const template = '{@select key=status}{@eq value="active"}Active User{/eq}{@eq value="inactive"}Inactive User{/eq}{/select}';
const compiled = dust.compile(template, 'user-status');
dust.loadSource(compiled);

dust.render('user-status', { status: 'active' }, (err, out) => {
  console.log(out); // "Active User"
});

Architecture

Dustjs Helpers is built around several key patterns:

  • UMD Module: Universal module definition supporting AMD, CommonJS, and browser globals
  • Helper Registration: All helpers are automatically registered with the dust instance during import
  • Context Helpers: Template helpers that operate on the Dust context and chunk system
  • Truth Testing: Conditional helpers that work with the {@select} helper for complex logic
  • Type Coercion: Built-in type conversion system for consistent comparisons
  • Deferred Rendering: Support for conditional rendering blocks with @any and @none

Capabilities

Mathematical Operations

Perform arithmetic calculations within templates with full precision control and error handling.

// @math helper performs mathematical operations
{@math key="operand1" method="operation" operand="operand2" round="boolean"/}
{@math key="operand1" method="operation" operand="operand2"}
  <!-- Optional body acts like @select -->
{/math}

Mathematical Operations

Conditional Logic and Selection

Create complex conditional template logic with type-safe comparisons and multiple test scenarios.

// @select groups truth tests and outputs the first match
{@select key="value" type="comparison_type"}
  {@eq value="test1"}Content for test1{/eq}
  {@ne value="test2"}Content when not test2{/ne}
  {@any}Content if any condition matched{/any}
  {@none}Content if no conditions matched{/none}
{/select}

Conditional Logic

Iteration and Context Helpers

Control rendering flow within loops and access iteration metadata for advanced template logic.

// Iteration control helpers
{@first}First item content{/first}
{@last}Last item content{/last}
{@sep}Separator content{/sep}

// Size calculation helper
{@size key="target_value"/}

Iteration Control

Utility and Debug Helpers

Debug templates and perform utility operations for template development and maintenance.

// Context debugging helper
{@contextDump key="full|current" to="console|template"/}

// Deprecated reference resolution (use native dust resolution)
{@tap}{reference}{/tap}

Utility Helpers

Registration Function

Manual helper registration for advanced use cases and custom dust instances.

// Manual registration function
function registerWith(dustInstance: DustInstance): DustInstance;

Usage:

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

// Register helpers with a specific dust instance
helpers.registerWith(dust);

// Now all helpers are available on dust.helpers
console.log(Object.keys(dust.helpers));
// ['tap', 'sep', 'first', 'last', 'contextDump', 'math', 'select', 'eq', 'ne', 'lt', 'lte', 'gt', 'gte', 'any', 'none', 'size']

Error Handling and Logging

Dustjs Helpers includes comprehensive error handling and logging:

  • Error Logging: All helpers use dust.log() to report errors and warnings
  • Graceful Degradation: Invalid parameters result in empty output rather than template crashes
  • Deprecation Warnings: Deprecated features show warnings with migration guidance
  • Type Coercion: Automatic type conversion for consistent behavior across helpers
  • Division by Zero: Math operations handle division by zero with NaN output and error logs

Common Error Scenarios:

// Missing required parameters
{@math method="add" operand="5"/}
// Logs: "{@math}: `key` or `method` was not provided"

// Division by zero
{@math key="10" method="divide" operand="0"/}
// Output: NaN, Logs: "{@math}: Division by 0"

// Invalid method
{@math key="10" method="invalid" operand="5"/}
// Logs: "{@math}: Method `invalid` is not supported"

// Missing select context
{@any}Content{/any}
// Logs: "{@any}: Must be used inside a {@select} block"

Types

// Module exports interface
interface DustjsHelpers {
  registerWith(dust: DustInstance): DustInstance;
  // All helpers are automatically registered on the provided dust instance
}

// All helpers follow this signature pattern
type HelperFunction = (
  chunk: DustChunk,
  context: DustContext,
  bodies: { block?: DustBody; else?: DustBody },
  params: Record<string, any>
) => DustChunk;

// Type coercion options for comparison helpers
type CoercionType = 'number' | 'string' | 'boolean' | 'date';

// Mathematical operations supported by @math
type MathMethod = 'add' | 'subtract' | 'multiply' | 'divide' | 'mod' | 'ceil' | 'floor' | 'round' | 'abs' | 'toint';

// Dust core types (provided by dustjs-linkedin)
interface DustInstance {
  helpers: Record<string, HelperFunction>;
  log(message: string, level?: string): void;
  // ... other dust methods
}

interface DustChunk {
  write(text: string | number): DustChunk;
  render(body: DustBody, context: DustContext): DustChunk;
  map(fn: (chunk: DustChunk) => void): DustChunk;
  end(): void;
}

interface DustContext {
  stack: {
    head: any;
    tail?: DustContext;
    index: number;
    of: number;
  };
  get(key: string): any;
  resolve(key: any): any;
  rebase(): DustContext;
  push(obj: any, idx?: number, len?: number): DustContext;
}

interface DustBody {
  (chunk: DustChunk, context: DustContext): DustChunk;
}

docs

conditional-logic.md

index.md

iteration-control.md

math-operations.md

utility-helpers.md

tile.json