### Install Bigodin with Bun
Source: https://jpbm135.github.io/bigodin/docs/tutorial/first-template
Install the Bigodin package using Bun.
```bash
bun add @jpbm135/bigodin
```
--------------------------------
### Install Bigodin with pnpm
Source: https://jpbm135.github.io/bigodin/docs/tutorial/first-template
Install the Bigodin package using pnpm.
```bash
pnpm add @jpbm135/bigodin
```
--------------------------------
### Install Bigodin with Bun
Source: https://jpbm135.github.io/bigodin/docs
Install the Bigodin library using Bun. Node.js version 20 or higher is required.
```bash
bun add @jpbm135/bigodin
```
--------------------------------
### Install Bigodin with Yarn
Source: https://jpbm135.github.io/bigodin/docs/tutorial/first-template
Install the Bigodin package using Yarn.
```bash
yarn add @jpbm135/bigodin
```
--------------------------------
### Playground Output Example
Source: https://jpbm135.github.io/bigodin/playground
Shows the rendered output of the template and context provided in the playground. This example illustrates the result of the template logic and helper functions.
```plaintext
Hello, WORLD!
You have 2 item(s):
- Apple (3)
- Pear (2)
Total quantity: 5.
```
--------------------------------
### Install Bigodin with npm
Source: https://jpbm135.github.io/bigodin/docs/tutorial/first-template
Install the Bigodin package using npm.
```bash
npm install @jpbm135/bigodin
```
--------------------------------
### Install Bigodin with pnpm
Source: https://jpbm135.github.io/bigodin/docs
Install the Bigodin library using pnpm. Node.js version 20 or higher is required.
```bash
pnpm add @jpbm135/bigodin
```
--------------------------------
### Clone Repository and Install Dependencies
Source: https://jpbm135.github.io/bigodin/docs/contributing
Clone the Bigodin repository and install its dependencies using Git and Yarn.
```bash
git clone https://github.com/JPBM135/bigodin.git
cd bigodin
yarn install
```
--------------------------------
### Bigodin Template Quick Example
Source: https://jpbm135.github.io/bigodin/docs/language
A quick example demonstrating conditional logic, array iteration, and accessing nested properties within a Bigodin template.
```handlebars
{{#if user.active}}
Welcome,
{{user.name}}! Your last 3 orders:
{{#each (slice user.orders 0 3)}}
-
{{@index}}.
{{this.product}}
({{this.total}})
{{/each}}
{{else}}
Account inactive.
{{/if}}
```
--------------------------------
### Registering an async database helper
Source: https://jpbm135.github.io/bigodin/docs/how-to/async-helpers
This example demonstrates registering an asynchronous helper 'user' that queries a database. The database connection is captured via closure when registering the helper. The helper takes a user ID and returns the corresponding user data.
```javascript
function registerHelpers(bigodin, db) {
bigodin.addHelper('user', async (id) => {
const row = await db.query('SELECT * FROM users WHERE id = $1', [id]);
return row[0];
});
}
const bigodin = new Bigodin();
registerHelpers(bigodin, db);
const template = bigodin.compile('{{#with (user id)}}{{name}}{{/with}}');
await template({ id: 42 });
```
--------------------------------
### Rendered Output After Stripping
Source: https://jpbm135.github.io/bigodin/docs/mustache-compat/standalone-line-whitespace
Shows the result after the standalone-line whitespace stripping is applied to the previous example.
```text
Hello
World
```
--------------------------------
### Install Bigodin with Yarn
Source: https://jpbm135.github.io/bigodin/docs
Install the Bigodin library using Yarn. Node.js version 20 or higher is required.
```bash
yarn add @jpbm135/bigodin
```
--------------------------------
### Install Bigodin using Yarn or npm
Source: https://jpbm135.github.io/bigodin
Install the Bigodin package using either Yarn or npm. This is the first step to using the templating engine.
```bash
yarn add bigodin
```
```bash
npm install bigodin
```
--------------------------------
### Install Bigodin with npm
Source: https://jpbm135.github.io/bigodin/docs
Install the Bigodin library using npm. Node.js version 20 or higher is required.
```bash
npm install @jpbm135/bigodin
```
--------------------------------
### Cache Key Construction with Bigodin Version
Source: https://jpbm135.github.io/bigodin/docs/explanation/ast-and-versioning
An example of how to construct a cache key that includes the Bigodin version. This ensures that old cache entries become stale and are automatically dropped when Bigodin is upgraded.
```javascript
const key = `bigodin:${BIGODIN_VERSION}:ast:${sha256(source)}`;
```
--------------------------------
### Registering and Using Custom Helpers
Source: https://jpbm135.github.io/bigodin/docs
Instantiate Bigodin to register custom helpers. This example adds a 'shout' helper to convert text to uppercase.
```javascript
const Bigodin = require('@jpbm135/bigodin').default;
const bigodin = new Bigodin();
bigodin.addHelper('shout', (s) => String(s).toUpperCase());
const template = bigodin.compile('Hello, {{shout name}}!');
await template({ name: 'world' }); // "Hello, WORLD!"
```
--------------------------------
### Example of Greedy Whitespace Trimming
Source: https://jpbm135.github.io/bigodin/docs/language/whitespace-control
Demonstrates how the trim is greedy, consuming all adjacent whitespace including newlines.
```Handlebars
a
{{~name~}}
b
```
--------------------------------
### Bound Template Execution with maxExecutionMillis
Source: https://jpbm135.github.io/bigodin/docs/tutorial/first-template
Use `maxExecutionMillis` to set a time budget for template rendering. If exceeded, an error is thrown. This example demonstrates setting a 50ms limit for a template with a slow helper.
```javascript
import Bigodin from '@jpbm135/bigodin';
const bigodin = new Bigodin();
bigodin.addHelper('slow', async () => {
await new Promise((r) => setTimeout(r, 200));
return 'done';
});
const template = bigodin.compile('Result: {{slow}}');
try {
await template({}, { maxExecutionMillis: 50 });
} catch (err) {
console.error(err.message);
// execution exceeded 50ms
}
```
--------------------------------
### Render Comma-Separated List with Iteration Variables
Source: https://jpbm135.github.io/bigodin/docs/language/iteration-variables
Use @index and @first/@last to format a list with specific start and end delimiters and commas between items.
```handlebars
{{#items}}{{#if @first}}[{{/if}}{{@index}}:{{$this}}{{#if @last}}]{{else}}, {{/if}}{{/items}}
```
--------------------------------
### Set Hard Wall-Clock Budget with maxExecutionMillis
Source: https://jpbm135.github.io/bigodin/docs/how-to/bound-execution-time
Use `maxExecutionMillis` in `RunOptions` to enforce a maximum execution time for template rendering. The runner checks this budget at the start of each statement.
```javascript
import Bigodin from '@jpbm135/bigodin';
const bigodin = new Bigodin();
bigodin.addHelper('slow', async () => {
await new Promise((r) => setTimeout(r, 200));
return 'done';
});
const template = bigodin.compile('Result: {{slow}}');
try {
await template({}, { maxExecutionMillis: 50 });
} catch (err) {
console.error(err.message); // execution exceeded 50ms
}
```
--------------------------------
### Example of Standalone-Line Whitespace Stripping
Source: https://jpbm135.github.io/bigodin/docs/mustache-compat/standalone-line-whitespace
Demonstrates how a line containing only a Mustache comment tag is stripped of its leading whitespace and trailing newline.
```mustache
Hello
{{! a comment }}
World
```
--------------------------------
### Surfacing data back to host via this.data
Source: https://jpbm135.github.io/bigodin/docs/how-to/async-helpers
This example shows how a helper can communicate data back to the host environment using `this.data`. The 'setTitle' helper updates a title property on `this.data`, which is accessible outside the template rendering. This is useful for page titles, meta tags, or accumulated warnings.
```javascript
bigodin.addHelper('setTitle', function (title) {
if (this.data) this.data.title = title;
return '';
});
const data = {};
const template = bigodin.compile('{{setTitle (uppercase headline)}}
{{headline}}
');
const html = await template({ headline: 'lorem ipsum' }, { data });
console.log(data.title); // "LOREM IPSUM"
console.log(html); // "lorem ipsum
"
```
--------------------------------
### Cooperative Early Exit with {{return}}
Source: https://jpbm135.github.io/bigodin/docs/tutorial/first-template
Implement cooperative early exit within a template using the `{{return}}` block. This stops rendering once encountered, as shown in this example where the template stops after 'Hello' if `shouldStop` is true.
```javascript
const template = bigodin.compile('Hello{{#if shouldStop}}{{return}}{{/if}}, world!');
console.log(await template({ shouldStop: true }));
// "Hello"
```
--------------------------------
### Run the script
Source: https://jpbm135.github.io/bigodin/docs/tutorial/first-template
Execute the Node.js script to see the rendered template output.
```bash
node step-1.mjs
```
--------------------------------
### Basic Template Rendering
Source: https://jpbm135.github.io/bigodin/playground
Demonstrates rendering a simple template with context. Includes helpers for uppercasing, length, addition, and JSON serialization. Note the execution budget.
```handlebars
Hello, {{shout name}}! {{#if items}} You have {{len items}} item(s): {{#each items}} - {{$this.label}} ({{$this.qty}}) {{/each}} {{= $total 0}} {{#each items}}{{= $total (add $total $this.qty)}}{{/each}} Total quantity: {{$total}}. {{else}} Your cart is empty. {{/if}}
```
```json
{ "name": "world", "items": [ {"label": "Apple", "qty": 3}, {"label": "Pear", "qty": 2} ] }
```
--------------------------------
### Instantiating Bigodin
Source: https://jpbm135.github.io/bigodin/docs/lib
Create a new instance of the Bigodin class. Each instance manages its own helper registry.
```javascript
const bigodin = new Bigodin();
```
--------------------------------
### Bigodin Class Instance Methods
Source: https://jpbm135.github.io/bigodin/docs/lib
Demonstrates the usage of the Bigodin class and its instance methods for custom helper registration, template compilation, parsing, and execution.
```APIDOC
## `class Bigodin`
Each instance owns its own helper registry. The instance methods mirror the module-level functions; the difference is that an instance's `compile`/`run` see its registered helpers.
### `bigodin.addHelper(name, fn)`
Register a helper for this instance.
* **`name: string`** must not match `__proto__` , `constructor`, `prototype`, or any other key blocked by `UNSAFE_KEYS`. Registering a forbidden name throws.
* **`fn: (...args) => any | Promise`** receives the `Execution` instance as `this` (see below). May be `async`. Non-string returns are coerced to string at the interpolation site.
Registering a helper with a name that already exists overwrites it. User helpers shadow built-in block helpers with the same name, and shadow context paths of the same name (a registered `name` helper wins over a `name` field in the context).
### `bigodin.compile(source)`
Parse `source` once and return a runner: `(context?, options?) => Promise`. Equivalent to `(ctx, opts) => run(parse(source), ctx, undefined, opts)` for this instance.
### `bigodin.parse(source)`
Parse `source` into a `TemplateStatement` AST. The result is plain JSON, safe to `JSON.stringify` and persist. Throws `BigodinParseError` on invalid syntax with `line` / `column` and an "expected ..." message.
### `bigodin.run(ast, context?, extraHelpers?, options?)`
Interpret a previously parsed AST. Returns `Promise`.
* **`ast`** is the output of `parse` , possibly round-tripped through JSON. The runner enforces a `[MIN_VERSION, MAX_VERSION]` window on `ast.version`; ASTs outside that window throw with a "parse it again" message. See AST and versioning.
* **`context`** is the root rendering context. Any JSON-like value. It is deep-cloned before the run, so your object is never mutated, and templates only ever read own, enumerable, non-function properties. Value-typed objects (`Date` , `RegExp`, `URL`, `Map`, `Set`, typed arrays) are cloned by value so helpers receive real instances; circular references and getters are handled safely. See The context clone.
* **`extraHelpers`** is an optional `Record` merged on top of the instance's helpers for this run only.
* **`options`** is documented under `RunOptions` below.
```
--------------------------------
### Global Variable Scope Example
Source: https://jpbm135.github.io/bigodin/docs/language/variables
Illustrates that variables are global. A variable $var is assigned outside a block, reassigned inside, and its final value is printed after the block.
```handlebars
{{= $var "global"}}
{{#condition}}
{{= $var "block"}}
{{/condition}}
Outside: {{ $var }}
```
--------------------------------
### Register a Basic Helper
Source: https://jpbm135.github.io/bigodin/docs/language/helpers
This snippet shows how to register a simple helper function named 'capitalize' using `addHelper`.
```javascript
bigodin.addHelper('capitalize', (s) => String(s).charAt(0).toUpperCase() + String(s).slice(1));
```
--------------------------------
### Importing Bigodin Compile and AddHelper
Source: https://jpbm135.github.io/bigodin/docs/lib
This code shows the correct way to import the 'compile' and 'addHelper' functions from the '@jpbm135/bigodin' module. It highlights that 'addHelper' is not a module-level export but an instance method.
```javascript
const { compile, addHelper } = require('@jpbm135/bigodin'); // there is no module-level addHelper
```
--------------------------------
### Basic Template Compilation and Rendering
Source: https://jpbm135.github.io/bigodin/docs
Compile a simple template string and render it with provided data. This demonstrates the basic usage of the `compile` function.
```javascript
const { compile } = require('@jpbm135/bigodin');
const template = compile('Hello, {{name}}!');
const result = await template({ name: 'George' });
// "Hello, George!"
```
--------------------------------
### Parse AST at Build Time and Write to File
Source: https://jpbm135.github.io/bigodin/docs/how-to/cache-parsed-asts
Parse a template once during your build or deployment process and save the resulting AST to a JSON file for later use.
```javascript
// build.mjs (run during deployment / startup)
import { parse } from '@jpbm135/bigodin';
import { writeFileSync } from 'node:fs';
const ast = parse('Hello, {{name}}!');
writeFileSync('greeting.ast.json', JSON.stringify(ast));
```
--------------------------------
### Render a template with a custom async helper
Source: https://jpbm135.github.io/bigodin
Demonstrates how to create a new Bigodin instance, add a custom asynchronous helper, parse a template string, and then run the template with provided data. The custom helper 'shout' converts the input string to uppercase.
```javascript
import {Bigodin} from 'bigodin';
const bigodin = new Bigodin();
bigodin.addHelper('shout', (s) => String(s).toUpperCase());
const ast = bigodin.parse('Hello, {{shout name}}!');
const out = await bigodin.run(ast, {name: 'world'});
// "Hello, WORLD!"
```
--------------------------------
### With Helper with Multiple Arguments
Source: https://jpbm135.github.io/bigodin/docs/helpers
Use `with` with multiple arguments to push each truthy argument onto the context stack as its own frame. Bare paths resolve against the innermost frame, and outer frames can be accessed with `$parent`.
```handlebars
{{#with user company}}
{{name}}
works at
{{$parent.name}}
{{/with}}
```
--------------------------------
### Using Async Helpers in Bigodin
Source: https://jpbm135.github.io/bigodin/docs/tutorial/first-template
Demonstrates how to define and use an asynchronous helper that fetches data and is transparently awaited by Bigodin. This is useful for integrating with external APIs or databases.
```javascript
import Bigodin from '@jpbm135/bigodin';
async function fetchUser(id) {
// pretend this is a real HTTP or DB call
await new Promise((r) => setTimeout(r, 50));
return { name: 'George', city: 'Lisbon' };
}
const bigodin = new Bigodin();
bigodin.addHelper('user', async (id) => fetchUser(id));
const template = bigodin.compile('{{#with (user id)}}{{name}} from {{city}}{{/with}}');
console.log(await template({ id: 42 }));
// "George from Lisbon"
```
--------------------------------
### Run AST from File at Request Time
Source: https://jpbm135.github.io/bigodin/docs/how-to/cache-parsed-asts
Load a pre-parsed AST from a JSON file and use it to render templates during request handling. This avoids parsing on every request.
```javascript
// server.mjs (request handler)
import { run } from '@jpbm135/bigodin';
import { readFileSync } from 'node:fs';
const ast = JSON.parse(readFileSync('greeting.ast.json', 'utf8'));
export async function render(context) {
return run(ast, context);
}
```
--------------------------------
### Call a Helper with Hash Arguments
Source: https://jpbm135.github.io/bigodin/docs/language/helpers
Demonstrates passing hash arguments (key-value pairs) to a helper, which are received as an options object.
```handlebars
{{link 'Sign up' target='_blank' rel='noopener'}}
```
--------------------------------
### Registering an async HTTP helper
Source: https://jpbm135.github.io/bigodin/docs/how-to/async-helpers
This snippet shows how to register an asynchronous helper named 'weather' that fetches temperature data from an external API. The helper takes a city name as input and returns the temperature. If the HTTP request fails, an error is thrown. Wrap the helper if retry logic is needed.
```javascript
import Bigodin from '@jpbm135/bigodin';
const bigodin = new Bigodin();
bigodin.addHelper('weather', async (city) => {
const res = await fetch(`https://api.example.com/weather?city=${encodeURIComponent(city)}`);
if (!res.ok) throw new Error(`weather lookup failed: ${res.status}`);
const { temperature } = await res.json();
return temperature;
});
const template = bigodin.compile('It is {{weather city}}°C in {{city}}.');
await template({ city: 'Lisbon' });
// "It is 18°C in Lisbon."
```
--------------------------------
### Parallel data fetching with multiple helpers
Source: https://jpbm135.github.io/bigodin/docs/how-to/async-helpers
This snippet illustrates how multiple helper parameters are evaluated in parallel. The 'combine' helper receives results from '(user id)' and '(orders id)' concurrently, demonstrating efficient parallel data fetching.
```handlebars
{{combine (user id) (orders id)}}
```
```javascript
bigodin.addHelper('combine', (user, orders) => `${user.name} has ${orders.length} orders`);
```
--------------------------------
### Register a Helper with Hash Arguments
Source: https://jpbm135.github.io/bigodin/docs/language/helpers
This snippet shows how to register a 'link' helper that accepts a label and hash arguments for attributes like 'target' and 'rel'.
```javascript
bigodin.addHelper('link', (label, options = {}) => {
const attrs = Object.entries(options)
.map(([k, v]) => `${k}="${v}"`)
.join(' ');
return `${label}`;
});
```
--------------------------------
### Persisting and Running Bigodin AST
Source: https://jpbm135.github.io/bigodin/docs/tutorial/first-template
Shows how to parse a Bigodin template into an AST, persist it to a file, and then reload and run it. This is beneficial for performance by parsing only once.
```javascript
import { parse, run } from '@jpbm135/bigodin';
import { writeFileSync, readFileSync } from 'node:fs';
// In your build step:
const ast = parse('Hello, {{name}}!');
writeFileSync('greeting.ast.json', JSON.stringify(ast));
// In your request handler, possibly in a different service:
const reloaded = JSON.parse(readFileSync('greeting.ast.json', 'utf8'));
console.log(await run(reloaded, { name: 'George' }));
// "Hello, George!"
```
--------------------------------
### Nested Loops with Block Parameters
Source: https://jpbm135.github.io/bigodin/docs/language/loop-blocks
Demonstrates using block parameters `as |item index|` to name the current item and index within nested loops. This allows referencing them by name, like `{{r}}` and `{{c}}`.
```handlebars
{{#each rows as |row r|}}
{{#each row as |cell c|}}
{{r}},{{c}}:
{{cell}}
{{/each}}
{{/each}}
```
--------------------------------
### Run Tests
Source: https://jpbm135.github.io/bigodin/docs/contributing
Ensure that all tests pass after making code changes.
```bash
yarn test
```
--------------------------------
### Reassigning Variables and Performing Calculations
Source: https://jpbm135.github.io/bigodin/docs/language/variables
Demonstrates reassignment and basic arithmetic operations. Variables $x and $y are initialized, then used to calculate $sum and $result.
```handlebars
{{= $x 1}}
{{= $y 2}}
{{= $sum (add $x $y)}}
{{= $result (multiply $sum 10)}}
Result: {{ $result }}
```
--------------------------------
### Walking Context Stack with `$parent` and `$root`
Source: https://jpbm135.github.io/bigodin/docs/language/context-blocks
Special variables like `$this`, `$parent`, and `$root` allow navigation of the context stack. `$parent` (or `../`) moves up one level, useful within loops or nested blocks.
```Handlebars
{{name}}, your comments:
{{#comments}} From {{author}} to {{../name}}:
{{comment}}
{{/comments}}
```
```json
{
"name": "George",
"comments": [
{
"author": "Alice",
"comment": "Nice presentation"
},
{
"author": "Bob",
"comment": "Thanks for the feedbacks"
}
]
}
```
```text
George, your comments:
From Alice to George:
Nice presentation
From Bob to George:
Thanks for the feedbacks
```
--------------------------------
### Running a parsed AST
Source: https://jpbm135.github.io/bigodin/docs/lib
Interpret a previously parsed AST to render the template. The AST version must be within the supported window. The context is deep-cloned before execution.
```javascript
bigodin.run(ast, context?, extraHelpers?, options?)
```
--------------------------------
### Compiling a template source
Source: https://jpbm135.github.io/bigodin/docs/lib
Parse template source code and return a runner function. This is equivalent to calling parse and then run for the instance.
```javascript
bigodin.compile(source)
```
--------------------------------
### Bigodin Template Processing Pipeline
Source: https://jpbm135.github.io/bigodin/docs/explanation/security-model
Illustrates the data flow from a template string to the final output string, highlighting the intermediate JSON AST.
```text
template string -> parser combinators -> JSON AST -> interpreter walks AST -> output string
```
--------------------------------
### Call Nested Helpers
Source: https://jpbm135.github.io/bigodin/docs/language/helpers
Shows how to use the result of one helper ('capitalize') as an argument to another ('default') using parentheses for subexpressions.
```handlebars
Hello, {{default (capitalize name) 'stranger'}}!
```
--------------------------------
### Iterating over a list of scalars with {{.}}
Source: https://jpbm135.github.io/bigodin/docs/mustache-compat/implicit-iterator
Demonstrates using `{{.}}` to iterate over a list of strings. This is equivalent to using `{{$this}}`.
```mustache
{{#items}}{{.}}{{/items}} {{!-- over ["a", "b", "c"] => "abc" --}}
{{#items}}{{$this}}{{/items}} {{!-- equivalent --}}
```
--------------------------------
### Nesting Loops and Accessing Outer Index
Source: https://jpbm135.github.io/bigodin/docs/language/iteration-variables
Demonstrates how inner loops shadow outer iteration variables and how to access outer variables using block parameters.
```handlebars
{{#each groups}}
Group
{{@index}}:
{{name}}
{{#each items}}
{{@index}}.
{{$this}}
{{/each}}
{{/each}}
```
```handlebars
{{#each groups as |group g|}}
{{#each group.items as |item i|}}
Outer
{{g}}, inner
{{i}}:
{{item}}
{{/each}}
{{/each}}
```
```handlebars
{{#each groups}}
{{= $groupIndex @index}}
Group {{@index}}: {{name}}
{{#each items}}
Outer {{$groupIndex}}, inner {{@index}}: {{$this}}
{{/each}}
{{/each}}
```
--------------------------------
### Safe HTML Rendering with Bigodin
Source: https://jpbm135.github.io/bigodin/docs/language/raw-output
Illustrates the recommended pattern for rendering HTML safely in Bigodin when using user-supplied context values. An 'e' helper is applied at interpolation sites for manual escaping.
```html
Hello, {{e name}}!
```
--------------------------------
### Hash Arguments in Helpers
Source: https://jpbm135.github.io/bigodin/docs/lib
Describes how to use and handle hash arguments (key=value pairs) in Big.js helpers.
```APIDOC
## Hash arguments
### Description
Helpers can receive Handlebars-style hash arguments (`key=value` pairs) after the positional parameters. These are passed as a single object.
### Usage in Template
```html
{{link 'Sign up' target='_blank' rel='noopener'}}
```
### Handling in Helper
When hash arguments are used, an object containing these key-value pairs is appended as the final argument to the helper function.
```javascript
bigodin.addHelper('link', (label, options = {}) => {
const attrs = Object.entries(options)
.map(([k, v]) => `${k}="${v}"`)
.join(' ');
return `${label}`;
});
```
### Notes
- Hash values can be literals, paths, variables, or subexpressions.
- Positional parameters are not allowed after a hash argument.
- Duplicate keys in hash arguments are rejected at parse time.
```
--------------------------------
### Call a Helper in a Template
Source: https://jpbm135.github.io/bigodin/docs/language/helpers
Demonstrates calling the 'capitalize' helper within a Bigodin template to format a name.
```handlebars
Hello, {{capitalize name}}!
```
--------------------------------
### Each Helper for Iteration
Source: https://jpbm135.github.io/bigodin/docs/helpers
The `each` helper iterates over an array, pushing each element as the current context. A non-array argument is treated as a single-element list. Empty arrays render nothing.
```handlebars
{{#each items}}
-
{{$this}}
{{/each}}
```
--------------------------------
### Simple Key Lookup
Source: https://jpbm135.github.io/bigodin/docs/language/path-expressions
Access a top-level key from the rendering context. Spaces within the braces are ignored.
```handlebars
Hello, {{name}}!
```
```json
{
"name": "George"
}
```
--------------------------------
### RunOptions Interface
Source: https://jpbm135.github.io/bigodin/docs/lib
Defines the options available when running a Big.js template, including execution time limits and data passing.
```APIDOC
## `RunOptions`
### Description
An interface defining the options that can be provided when running a Big.js template.
### Properties
- **`maxExecutionMillis`** (number, optional): Maximum execution time in milliseconds. If exceeded, the run throws an error. Useful for bounding runtime on untrusted input.
- **`data`** (Record, optional): A data object passed to helpers as `this.data`. Templates cannot read this directly, but helpers can mutate it to return structured data.
- **`allowDefaultHelpers`** (boolean, optional): Defaults to `true`. If set to `false`, the bundled block helpers (like `if`, `unless`, `each`) are disabled. Helpers added via `addHelper` are always executed.
### Example Usage
```javascript
const options = {
maxExecutionMillis: 5000,
data: { userId: 123 },
allowDefaultHelpers: false
};
// Assuming 'bigodin' is your Big.js instance
// bigodin.render(template, data, options);
```
```
--------------------------------
### Compiling a single expression
Source: https://jpbm135.github.io/bigodin/docs/lib
Parse and prepare a single expression for execution. Returns a runner function.
```javascript
bigodin.compileExpression(source)
```
--------------------------------
### Expression Methods
Source: https://jpbm135.github.io/bigodin/docs/lib
Details on methods for parsing, running, and compiling single expressions, useful for evaluating mustache-shaped values.
```APIDOC
### `bigodin.parseExpression(source)`, `bigodin.runExpression(ast, context?, options?)`, `bigodin.compileExpression(source)`
Same as `parse` / `run` / `compile`, but for a single expression rather than a full template. Useful when you want to evaluate one mustache-shaped value without surrounding text. The expression is the body of a `{{...}}` minus the braces.
```
--------------------------------
### Running a single expression
Source: https://jpbm135.github.io/bigodin/docs/lib
Interpret a previously parsed expression AST. Returns a Promise.
```javascript
bigodin.runExpression(ast, context?, options?)
```
--------------------------------
### Importing Bigodin with CommonJS
Source: https://jpbm135.github.io/bigodin/docs/lib
Import the default Bigodin class and other functions using CommonJS syntax.
```javascript
const Bigodin = require('@jpbm135/bigodin').default;
const {
compile,
compileExpression,
parse,
parseExpression,
run,
runExpression,
} = require('@jpbm135/bigodin');
```
--------------------------------
### With Helper for Context Change
Source: https://jpbm135.github.io/bigodin/docs/helpers
The `with` helper pushes a value as the new context for the duration of the block. Inside the block, bare paths resolve against the new context. The block runs exactly once. Falsy values render the `else` branch.
```handlebars
{{#with user.address}}
{{street}},
{{city}}
{{/with}}
```
--------------------------------
### Importing Bigodin with ES Modules
Source: https://jpbm135.github.io/bigodin/docs/lib
Import the default Bigodin class and other functions using ES Module syntax.
```javascript
import Bigodin, {
compile,
compileExpression,
parse,
parseExpression,
run,
runExpression,
} from '@jpbm135/bigodin';
```
--------------------------------
### Execution Context (`this`) in Helpers
Source: https://jpbm135.github.io/bigodin/docs/lib
Explains the properties available within the `this` context inside a helper function.
```APIDOC
## `Execution` (the helper `this`)
### Description
Every helper is invoked with an `Execution` instance bound to `this`, providing access to runtime information and control.
### Properties
- **`this.data`** (Record): The `data` object from `RunOptions`. Helpers may mutate this to return structured data.
- **`this.halt()`**: Stops the execution of the template and returns whatever has been emitted so far.
- **`this.contexts`** (Array): The context stack (read-only).
- **`this.variables`** (Object): Assignments made using `{{= $var ...}}` for the current run.
### Example Usage
```javascript
bigodin.addHelper('processData', function () {
// Access and potentially mutate data
if (this.data) {
this.data.processed = true;
}
// Stop execution if needed
// this.halt();
});
```
```
--------------------------------
### Basic Comment Usage
Source: https://jpbm135.github.io/bigodin/docs/language/comments
Use `{{! ... }}` to add comments that will be excluded from the final output. This is useful for explaining template logic.
```html
{{! greeting the user }}
Hello,
{{name}}
:)
```
--------------------------------
### Include Version in Cache Key
Source: https://jpbm135.github.io/bigodin/docs/how-to/cache-parsed-asts
A strategy to mitigate version mismatches by including the Bigodin version or deploy ID in the cache key, ensuring cache invalidation on updates.
```javascript
const key = `bigodin:${BIGODIN_VERSION}:ast:${hash}`;
```
--------------------------------
### Programmatic Early Exit from Helper with this.halt()
Source: https://jpbm135.github.io/bigodin/docs/how-to/bound-execution-time
Inside a helper, call `this.halt()` to stop the rendering process immediately. The output emitted up to that point will be returned.
```javascript
bigodin.addHelper('requireAuth', function () {
if (!this.data?.user) {
this.halt();
return '';
}
return '';
});
const template = bigodin.compile('{{requireAuth}}Hello, {{name}}! Your private content here.');
const result = await template({ name: 'George' }, { data: {} });
// "" — halted before the greeting was emitted
```
--------------------------------
### Distinguish Path Lookup from Helper Call
Source: https://jpbm135.github.io/bigodin/docs/language/helpers
Illustrates how to explicitly force a path lookup using '$this.' when a helper name might conflict with a context path.
```handlebars
{{uuid}}
{{! calls uuid() if registered, else reads "uuid" from context }}
{{$this.uuid}}
{{! always reads "uuid" from the current context }}
```
--------------------------------
### Handle Version Mismatches with Fallback
Source: https://jpbm135.github.io/bigodin/docs/how-to/cache-parsed-asts
Implement a render function that includes a fallback mechanism to re-parse the template and update the cache if a version mismatch error occurs.
```javascript
import { parse, run } from '@jpbm135/bigodin';
async function renderWithFallback(redis, source, context) {
let ast = await getCachedAst(redis, source);
try {
return await run(ast, context);
} catch (err) {
if (!err.message?.includes('parse')) throw err;
// version mismatch — re-parse and replace the cache entry
ast = parse(source);
await redis.set(cacheKey(source), JSON.stringify(ast), 'EX', 86400);
return run(ast, context);
}
}
```
--------------------------------
### Call a Helper with Default Value
Source: https://jpbm135.github.io/bigodin/docs/language/helpers
Illustrates using the 'default' helper to provide a fallback value if a variable is not present.
```handlebars
Hello, {{default name 'stranger'}}!
```
--------------------------------
### Register and use a custom helper
Source: https://jpbm135.github.io/bigodin/docs/tutorial/first-template
Instantiate `Bigodin` directly to add custom helpers. The 'shout' helper converts its argument to uppercase. Helpers are positional and can accept literals or nested calls.
```javascript
import Bigodin from '@jpbm135/bigodin';
const bigodin = new Bigodin();
bigodin.addHelper('shout', (s) => String(s).toUpperCase());
const template = bigodin.compile('Hello, {{shout name}}!');
console.log(await template({ name: 'world' }));
// "Hello, WORLD!"
```
--------------------------------
### Whitespace Control on Different Tag Types
Source: https://jpbm135.github.io/bigodin/docs/language/whitespace-control
Shows the application of '~' for whitespace control across various Bigodin tag types.
```Handlebars
{{~x~}}
```
```Handlebars
{{~{x}~}}
```
```Handlebars
{{~&x~}}
```
```Handlebars
{{~! note ~}}
```
```Handlebars
{{~= $v 1 ~}}
```
```Handlebars
{{~#if x~}}
```
```Handlebars
{{~/if~}}
```
```Handlebars
{{~else~}}
```
--------------------------------
### RunOptions Interface
Source: https://jpbm135.github.io/bigodin/docs/lib
Defines the options available when running Big.js operations. Use maxExecutionMillis to bound runtime and data for passing information to helpers.
```typescript
interface RunOptions {
maxExecutionMillis?: number;
data?: Record;
allowDefaultHelpers?: boolean;
}
```
--------------------------------
### Basic Negated Block Usage
Source: https://jpbm135.github.io/bigodin/docs/language/negated-blocks
Use this snippet to render content when a variable is falsy (null, undefined, false, 0, '', NaN, or empty array).
```handlebars
{{^name}}
You are not logged in
{{/name}}
```
--------------------------------
### Iterating with Block Params
Source: https://jpbm135.github.io/bigodin/docs/language/block-params
Use `as |name index|` on an `{{#each}}` block to name the current item and its index. These names are scoped to the block body and shadow context keys of the same name.
```handlebars
{{#each users as |user index|}}
{{index}}.
{{user.name}}
{{/each}}
```
--------------------------------
### Raw Output with Triple Mustache and Ampersand
Source: https://jpbm135.github.io/bigodin/docs/mustache-compat/triple-mustache-and-ampersand
In Bigodin, `{{x}}`, `{{{x}}}`, and `{{&x}}` all emit raw values. The triple-brace and ampersand forms are accepted for spec compatibility and function the same as the standard `{{x}}` form.
```mustache
{{x}}
=> raw value
{{{x}}}
=> raw value (same as
{{x}})
{{{x}}}
=> raw value (same as
{{x}})
```
--------------------------------
### Round-trip AST serialization and deserialization
Source: https://jpbm135.github.io/bigodin/docs/explanation/ast-and-versioning
Illustrates the AST round-trip capability, where an AST generated by `parse` can be serialized to JSON and then deserialized back, producing a compatible AST for the `run` function.
```javascript
JSON.parse(JSON.stringify(parse(source)));
```
--------------------------------
### Handling Missing Keys
Source: https://jpbm135.github.io/bigodin/docs/language/path-expressions
A missing key resolves to an empty string. Bigodin does not walk the context stack by default; use $parent or $root for explicit navigation.
```handlebars
[{{missing}}]
```
--------------------------------
### Bigodin Version Window Constants
Source: https://jpbm135.github.io/bigodin/docs/explanation/ast-and-versioning
Defines the minimum and maximum supported AST versions for the runner. Versions outside this window will cause the runner to reject the AST.
```typescript
const MIN_VERSION = 1;
const MAX_VERSION = 5;
```
--------------------------------
### Basic If Helper
Source: https://jpbm135.github.io/bigodin/docs/helpers
Use the `if` helper to conditionally render a block of content when a value is truthy. The context is not changed within the block. An optional `else` branch can be provided for falsy values.
```handlebars
{{#if user.active}}
Welcome,
{{user.name}}!
{{else}}
Account inactive.
{{/if}}
```
--------------------------------
### Return Helper to Halt Execution
Source: https://jpbm135.github.io/bigodin/docs/helpers
The `return` helper halts the rest of the template execution. The runner returns whatever output has accumulated up to that point.
```handlebars
Hello{{#if shouldStop}}{{return}}{{/if}}, world!
```
--------------------------------
### Execution Context for Helpers
Source: https://jpbm135.github.io/bigodin/docs/lib
Illustrates the 'this' context available within Big.js helpers. It provides access to run options data, allows halting execution, and exposes context and variable stacks.
```javascript
bigodin.addHelper('myHelper', function (...args) {
this.data; // the RunOptions.data object (may be undefined)
this.halt(); // stop execution; the run returns whatever has been emitted so far
this.contexts; // the context stack (read-only by convention)
this.variables; // {{= $var ...}} assignments for this run
});
```
--------------------------------
### Iterating Over an Array of Comments
Source: https://jpbm135.github.io/bigodin/docs/language/loop-blocks
Demonstrates iterating over a 'comments' array to display author and comment content. The body runs once per element, pushing the element as the current context.
```handlebars
{{name}}, your comments:
{{#comments}}
{{author}}
wrote:
{{comment}}
{{/comments}}
```
--------------------------------
### Cooperative Early Exit from Template with {{return}}
Source: https://jpbm135.github.io/bigodin/docs/how-to/bound-execution-time
The `{{return}}` block allows template authors to implement a cooperative early exit. It's typically wrapped in a conditional block like `{{#if}}`.
```handlebars
const template = bigodin.compile('Hello{{#if shouldStop}}{{return}}{{/if}}, world!');
console.log(await template({ shouldStop: true })); // "Hello"
console.log(await template({ shouldStop: false })); // "Hello, world!"
```
--------------------------------
### Registering an Interpolation Helper
Source: https://jpbm135.github.io/bigodin/docs/mustache-compat/lambdas
Register a helper function to be used for interpolation. The helper's return value will be substituted directly.
```javascript
bigodin.addHelper('greet', (name) => `Hello, ${name}!`);
```