Context helpers that extend the core Dust.js templating system with conditional logic, mathematical operations, and iteration utilities.
npx @tessl/cli install tessl/npm-dustjs-helpers@1.7.00
# Dustjs Helpers
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: dustjs-helpers
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install dustjs-helpers`
10
11
## Core Imports
12
13
**CommonJS (Node.js) - Primary usage pattern:**
14
15
```javascript
16
const dustjsHelpers = require('dustjs-helpers');
17
// Auto-registers all helpers with the dust instance provided by dustjs-linkedin
18
```
19
20
**Manual registration with existing dust instance:**
21
22
```javascript
23
const dust = require('dustjs-linkedin');
24
const dustjsHelpers = require('dustjs-helpers');
25
dustjsHelpers.registerWith(dust);
26
```
27
28
**AMD module (RequireJS):**
29
30
```javascript
31
define(['dust.core'], function(dust) {
32
// When using AMD, specify dust.core as dependency
33
define(['dustjs-helpers'], function(helpers) {
34
// helpers are automatically registered with dust
35
return helpers;
36
});
37
});
38
```
39
40
**Browser (Script tag):**
41
42
```html
43
<script src="dust.js"></script>
44
<script src="dustjs-helpers.js"></script>
45
<!-- Helpers are automatically registered with window.dust -->
46
```
47
48
**Browser (UMD pattern):**
49
50
```javascript
51
(function() {
52
// If dust is available globally, helpers register automatically
53
if (typeof dust !== 'undefined') {
54
// Helpers are now available on dust.helpers
55
dust.render(template, context, callback);
56
}
57
})();
58
```
59
60
## Basic Usage
61
62
All helpers are used within Dust.js templates using the `{@helperName}` syntax:
63
64
```javascript
65
// Template compilation and rendering
66
const dust = require('dustjs-linkedin');
67
require('dustjs-helpers'); // Auto-registers helpers
68
69
const template = '{@select key=status}{@eq value="active"}Active User{/eq}{@eq value="inactive"}Inactive User{/eq}{/select}';
70
const compiled = dust.compile(template, 'user-status');
71
dust.loadSource(compiled);
72
73
dust.render('user-status', { status: 'active' }, (err, out) => {
74
console.log(out); // "Active User"
75
});
76
```
77
78
## Architecture
79
80
Dustjs Helpers is built around several key patterns:
81
82
- **UMD Module**: Universal module definition supporting AMD, CommonJS, and browser globals
83
- **Helper Registration**: All helpers are automatically registered with the dust instance during import
84
- **Context Helpers**: Template helpers that operate on the Dust context and chunk system
85
- **Truth Testing**: Conditional helpers that work with the {@select} helper for complex logic
86
- **Type Coercion**: Built-in type conversion system for consistent comparisons
87
- **Deferred Rendering**: Support for conditional rendering blocks with @any and @none
88
89
## Capabilities
90
91
### Mathematical Operations
92
93
Perform arithmetic calculations within templates with full precision control and error handling.
94
95
```javascript { .api }
96
// @math helper performs mathematical operations
97
{@math key="operand1" method="operation" operand="operand2" round="boolean"/}
98
{@math key="operand1" method="operation" operand="operand2"}
99
<!-- Optional body acts like @select -->
100
{/math}
101
```
102
103
[Mathematical Operations](./math-operations.md)
104
105
### Conditional Logic and Selection
106
107
Create complex conditional template logic with type-safe comparisons and multiple test scenarios.
108
109
```javascript { .api }
110
// @select groups truth tests and outputs the first match
111
{@select key="value" type="comparison_type"}
112
{@eq value="test1"}Content for test1{/eq}
113
{@ne value="test2"}Content when not test2{/ne}
114
{@any}Content if any condition matched{/any}
115
{@none}Content if no conditions matched{/none}
116
{/select}
117
```
118
119
[Conditional Logic](./conditional-logic.md)
120
121
### Iteration and Context Helpers
122
123
Control rendering flow within loops and access iteration metadata for advanced template logic.
124
125
```javascript { .api }
126
// Iteration control helpers
127
{@first}First item content{/first}
128
{@last}Last item content{/last}
129
{@sep}Separator content{/sep}
130
131
// Size calculation helper
132
{@size key="target_value"/}
133
```
134
135
[Iteration Control](./iteration-control.md)
136
137
### Utility and Debug Helpers
138
139
Debug templates and perform utility operations for template development and maintenance.
140
141
```javascript { .api }
142
// Context debugging helper
143
{@contextDump key="full|current" to="console|template"/}
144
145
// Deprecated reference resolution (use native dust resolution)
146
{@tap}{reference}{/tap}
147
```
148
149
[Utility Helpers](./utility-helpers.md)
150
151
### Registration Function
152
153
Manual helper registration for advanced use cases and custom dust instances.
154
155
```javascript { .api }
156
// Manual registration function
157
function registerWith(dustInstance: DustInstance): DustInstance;
158
```
159
160
**Usage:**
161
162
```javascript
163
const dust = require('dustjs-linkedin');
164
const helpers = require('dustjs-helpers');
165
166
// Register helpers with a specific dust instance
167
helpers.registerWith(dust);
168
169
// Now all helpers are available on dust.helpers
170
console.log(Object.keys(dust.helpers));
171
// ['tap', 'sep', 'first', 'last', 'contextDump', 'math', 'select', 'eq', 'ne', 'lt', 'lte', 'gt', 'gte', 'any', 'none', 'size']
172
```
173
174
## Error Handling and Logging
175
176
Dustjs Helpers includes comprehensive error handling and logging:
177
178
- **Error Logging**: All helpers use `dust.log()` to report errors and warnings
179
- **Graceful Degradation**: Invalid parameters result in empty output rather than template crashes
180
- **Deprecation Warnings**: Deprecated features show warnings with migration guidance
181
- **Type Coercion**: Automatic type conversion for consistent behavior across helpers
182
- **Division by Zero**: Math operations handle division by zero with `NaN` output and error logs
183
184
**Common Error Scenarios:**
185
186
```javascript
187
// Missing required parameters
188
{@math method="add" operand="5"/}
189
// Logs: "{@math}: `key` or `method` was not provided"
190
191
// Division by zero
192
{@math key="10" method="divide" operand="0"/}
193
// Output: NaN, Logs: "{@math}: Division by 0"
194
195
// Invalid method
196
{@math key="10" method="invalid" operand="5"/}
197
// Logs: "{@math}: Method `invalid` is not supported"
198
199
// Missing select context
200
{@any}Content{/any}
201
// Logs: "{@any}: Must be used inside a {@select} block"
202
```
203
204
## Types
205
206
```javascript { .api }
207
// Module exports interface
208
interface DustjsHelpers {
209
registerWith(dust: DustInstance): DustInstance;
210
// All helpers are automatically registered on the provided dust instance
211
}
212
213
// All helpers follow this signature pattern
214
type HelperFunction = (
215
chunk: DustChunk,
216
context: DustContext,
217
bodies: { block?: DustBody; else?: DustBody },
218
params: Record<string, any>
219
) => DustChunk;
220
221
// Type coercion options for comparison helpers
222
type CoercionType = 'number' | 'string' | 'boolean' | 'date';
223
224
// Mathematical operations supported by @math
225
type MathMethod = 'add' | 'subtract' | 'multiply' | 'divide' | 'mod' | 'ceil' | 'floor' | 'round' | 'abs' | 'toint';
226
227
// Dust core types (provided by dustjs-linkedin)
228
interface DustInstance {
229
helpers: Record<string, HelperFunction>;
230
log(message: string, level?: string): void;
231
// ... other dust methods
232
}
233
234
interface DustChunk {
235
write(text: string | number): DustChunk;
236
render(body: DustBody, context: DustContext): DustChunk;
237
map(fn: (chunk: DustChunk) => void): DustChunk;
238
end(): void;
239
}
240
241
interface DustContext {
242
stack: {
243
head: any;
244
tail?: DustContext;
245
index: number;
246
of: number;
247
};
248
get(key: string): any;
249
resolve(key: any): any;
250
rebase(): DustContext;
251
push(obj: any, idx?: number, len?: number): DustContext;
252
}
253
254
interface DustBody {
255
(chunk: DustChunk, context: DustContext): DustChunk;
256
}
257
```