Skip to main content

bomboni_template

Utilities for working with Handlebars templates. This crate provides a collection of custom Handlebars helpers for template rendering, including helpers for mathematical operations, string transformations, value manipulation, conditional logic, and dynamic template rendering.

Main Function

register_helpers

Registers all template helpers with the Handlebars registry.
pub fn register_helpers(handlebars_registry: &mut Handlebars)

Example

use handlebars::Handlebars;
use bomboni_template::helpers::register_helpers;

let mut hbs = Handlebars::new();
register_helpers(&mut hbs);

// Now you can use all helpers
let result = hbs.render_template("{{add 1 2}}", &serde_json::Value::Null).unwrap();
assert_eq!(result, "3.0");

Math Helpers

Mathematical operations on numbers.

Binary Operations

add - Addition
{{add 5 3}}  {{!-- 8.0 --}}
{{add a b}}
subtract - Subtraction
{{subtract 10 3}}  {{!-- 7.0 --}}
{{subtract x y}}
multiply - Multiplication
{{multiply 4 5}}  {{!-- 20.0 --}}
{{multiply width height}}
divide - Division
{{divide 10 2}}  {{!-- 5.0 --}}
{{divide total count}}
modulo - Modulo operation
{{modulo 10 3}}  {{!-- 1.0 --}}
{{modulo value divisor}}

Unary Operations

negate - Negate value
{{negate 5}}  {{!-- -5.0 --}}
{{negate x}}
absolute - Absolute value
{{absolute -5}}  {{!-- 5.0 --}}
{{absolute delta}}
round - Round to nearest integer
{{round 3.7}}  {{!-- 4.0 --}}
{{round value}}
ceil - Ceiling (round up)
{{ceil 3.1}}  {{!-- 4.0 --}}
{{ceil x}}
floor - Floor (round down)
{{floor 3.9}}  {{!-- 3.0 --}}
{{floor y}}
sqrt - Square root
{{sqrt 16}}  {{!-- 4.0 --}}
{{sqrt 2}}   {{!-- 1.4142135623730951 --}}
sign - Sign of number (-1, 0, or 1)
{{sign -5}}  {{!-- -1.0 --}}
{{sign 0}}   {{!-- 0.0 --}}
{{sign 5}}   {{!-- 1.0 --}}

Advanced Operations

pow - Power (x^p)
{{pow 2 8}}  {{!-- 256.0 --}}
{{pow base exponent}}
clamp - Clamp value between min and max
{{clamp 5 1 3}}    {{!-- 3.0 --}}
{{clamp -1 0 10}}  {{!-- 0.0 --}}
{{clamp 7 0 10}}   {{!-- 7.0 --}}

String Helpers

String manipulation and case conversion.

Case Conversion

upperCase - UPPER CASE
{{upperCase "hello world"}}  {{!-- HELLO WORLD --}}
lowerCase - lower case
{{lowerCase "HELLO WORLD"}}  {{!-- hello world --}}
titleCase - Title Case
{{titleCase "hello world"}}  {{!-- Hello World --}}
camelCase - camelCase
{{camelCase "hello world"}}  {{!-- helloWorld --}}
{{camelCase "user_name"}}    {{!-- userName --}}
pascalCase - PascalCase
{{pascalCase "hello world"}}  {{!-- HelloWorld --}}
{{pascalCase "user_name"}}    {{!-- UserName --}}
snakeCase - snake_case
{{snakeCase "hello world"}}  {{!-- hello_world --}}
{{snakeCase "userName"}}     {{!-- user_name --}}
screamingSnakeCase - SCREAMING_SNAKE_CASE
{{screamingSnakeCase "hello world"}}  {{!-- HELLO_WORLD --}}
kebabCase - kebab-case
{{kebabCase "hello world"}}  {{!-- hello-world --}}
trainCase - Train-Case
{{trainCase "hello world"}}  {{!-- Hello-World --}}
Other case helpers: toggleCase, alternatingCase, upperCamelCase, upperSnakeCase, cobolCase, flatCase, upperFlatCase

String Formatting

toString - Convert value to string
{{toString 42}}      {{!-- "42" --}}
{{toString myValue}}
toJson - Convert to JSON
{{toJson object}}
{{toJson object pretty=true}}  {{!-- Pretty-printed --}}
concat - Concatenate multiple values
{{concat "Hello" " " "World"}}  {{!-- Hello World --}}
{{concat firstName " " lastName}}
toIntegerString - Convert to integer string
{{toIntegerString 3.14}}  {{!-- "3" --}}
{{toIntegerString value}}

Value Helpers

Create and manipulate data structures.

Object Operations

object - Create object from named parameters
{{object name="John" age=30 active=true}}
{{!-- { "name": "John", "age": 30, "active": true } --}}
objectHasKey - Check if object has key
{{objectHasKey user "email"}}  {{!-- true/false --}}
{{objectHasKey (object x=42) "x"}}  {{!-- true --}}

Array Operations

array - Create array from parameters
{{array 1 2 3 4}}  {{!-- [1, 2, 3, 4] --}}
{{array "a" "b" "c"}}
groupBy - Group array by key
{{groupBy items "category"}}
{{!-- Groups items by their category field --}}
Example:
{{toJson (groupBy (array (object x=1 y=2) (object x=2 y=4)) "x")}}
{{!-- {"1":[{"x":1,"y":2}],"2":[{"x":2,"y":4}]} --}}
contains - Check if haystack contains needle
{{contains (array 1 2 3 4) 2}}     {{!-- true --}}
{{contains "hello world" "world"}} {{!-- true --}}
{{contains object "key"}}          {{!-- checks if key exists --}}
filter - Filter array by predicate template
{{filter users "{{#if active}}true{{/if}}"}}
{{filter items "{{#if (gt price 100)}}true{{/if}}" includeZero=true}}

Truthiness Checks

none - Check if all values are falsy
{{none false 0}}  {{!-- true --}}
{{none a b c includeZero=true}}
all - Check if all values are truthy
{{all true 1 "text"}}  {{!-- true --}}
{{all a b c includeZero=false}}
some - Check if some value is truthy
{{some false true false}}  {{!-- true --}}
{{some a b c}}

Conditional Helpers

orElse - Return item if truthy, else fallback
{{orElse value "default"}}
{{orElse user.name "Anonymous"}}
andThen - Return fallback if item truthy, else item
{{andThen condition "yes" "no"}}
eitherOr - Conditional value selection
{{eitherOr condition "left" "right"}}
{{eitherOr isAdmin "Admin" "User"}}
All conditional helpers support includeZero parameter to control whether 0 is treated as truthy:
{{orElse 0 "default" includeZero=true}}   {{!-- 0 --}}
{{orElse 0 "default" includeZero=false}}  {{!-- "default" --}}

Switch Helper

Switch/case pattern matching for templates. switch - Begin switch statement case - Match one or more values default - Fallback when no case matches

Basic Example

{{#switch status}}
  {{#case "active"}}Active User{{/case}}
  {{#case "pending"}}Pending Approval{{/case}}
  {{#case "suspended"}}Account Suspended{{/case}}
  {{#default}}Unknown Status{{/default}}
{{/switch}}

Multi-Value Matching

{{#switch x}}
  {{#case 42}}The answer{{/case}}
  {{#case 2 4 8}}Power of two: {{@value}}{{/case}}
  {{#case "foo" "bar" "baz"}}Funny word: {{@value}}{{/case}}
  {{#default}}Number: {{@value}}{{/default}}
{{/switch}}
The @value variable inside case/default blocks contains the matched value.

Nested Switch

{{#switch type}}
  {{#case "int" "long"}}
    signed ({{@value}}):
    {{#switch size}}
      {{#case 1 2 4}}type={{@../value}} size={{@value}}{{/case}}
      {{#default}}unsupported{{/default}}
    {{/switch}}
  {{/case}}
  {{#case "uint" "ulong"}}unsigned{{/case}}
{{/switch}}

Render and Decorators

Dynamic template rendering and local variables.

render Helper

render - Dynamically render template string
{{render "Hello {{name}}!"}}
{{render template}}
Example with data:
{{render "x = {{x}}"}}
{{!-- With data: {"x": 42} → "x = 42" --}}

set Decorator

set - Set local variables (decorator syntax)
{{*set name="John" age=30}}
{{@name}} is {{@age}} years old.
{{!-- John is 30 years old. --}}
Local variables are accessed with @ prefix.

Combined Example

{{*set greeting="Hello" target="World"}}
{{render "{{greeting}}, {{target}}!"}}
{{!-- Hello, World! --}}

Complete Example

use handlebars::Handlebars;
use serde_json::json;
use bomboni_template::helpers::register_helpers;

let mut hbs = Handlebars::new();
register_helpers(&mut hbs);

let template = r#"
{{*set apiName=(pascalCase service_name)}}
/**
 * {{titleCase service_name}} Service
 * Total endpoints: {{add (length routes) 1}}
 */
export class {{@apiName}} {
  {{#each routes}}
  {{#switch method}}
    {{#case "GET" "POST"}}
    async {{camelCase name}}({{#if params}}params: Params{{/if}}): Promise<Response> {
      const url = `{{concat baseUrl path}}`;
      return fetch(url, { method: '{{@value}}' });
    }
    {{/case}}
  {{/switch}}
  {{/each}}
}
"#;

let data = json!({
    "service_name": "user_management",
    "baseUrl": "/api/v1",
    "routes": [
        {"name": "get_user", "method": "GET", "path": "/users/:id", "params": true},
        {"name": "create_user", "method": "POST", "path": "/users", "params": true}
    ]
});

let result = hbs.render_template(template, &data).unwrap();
println!("{}", result);

Helper Categories

Math Helpers

add, subtract, multiply, divide, modulo, negate, absolute, round, ceil, floor, sqrt, sign, pow, clamp

String Helpers

upperCase, lowerCase, titleCase, toggleCase, alternatingCase, camelCase, pascalCase, upperCamelCase, snakeCase, upperSnakeCase, screamingSnakeCase, kebabCase, cobolCase, trainCase, flatCase, upperFlatCase, toString, toJson, concat, toIntegerString

Value Helpers

object, objectHasKey, array, groupBy, contains, none, all, some, filter, orElse, andThen, eitherOr

Switch Helper

switch, case, default

Render and Decorators

render, set Based on Handlebars templating language.

Build docs developers (and LLMs) love