or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-string-template

A simple string template function based on named or indexed arguments

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/string-template@1.0.x

To install, run

npx @tessl/cli install tessl/npm-string-template@1.0.0

index.mddocs/

String Template

String Template is a simple, lightweight JavaScript string templating library that enables placeholder-based string formatting using named object properties, indexed array elements, or variadic arguments. It provides high-performance template compilation options and supports escaping syntax for literal braces.

Package Information

  • Package Name: string-template
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install string-template

Core Imports

var format = require("string-template");
var compile = require("string-template/compile");

Basic Usage

var format = require("string-template");

// Object-based placeholders
var greeting = format("Hello {name}, you have {count} unread messages", {
    name: "Robert",
    count: 12
});
// Result: "Hello Robert, you have 12 unread messages"

// Array-based placeholders
var message = format("Hello {0}, you have {1} unread messages", ["Alice", 5]);
// Result: "Hello Alice, you have 5 unread messages"

// Variadic arguments
var text = format("Hello {0}, you have {1} unread messages", "Bob", 3);
// Result: "Hello Bob, you have 3 unread messages"

// Escaping placeholders
var escaped = format("Use {{placeholder}} syntax for templates");
// Result: "Use {placeholder} syntax for templates"

Capabilities

String Template Function

Main templating function that replaces placeholders in strings with provided values.

/**
 * Template function for string interpolation with placeholder substitution
 * @param {string} string - Template string containing {placeholder} markers
 * @param {object|array} args - Single object/array OR multiple arguments
 * @returns {string} Formatted string with placeholders replaced
 */
function template(string, args);

Placeholder Syntax:

  • Format: {key} where key matches pattern [0-9a-zA-Z_]+
  • Escaping: {{key}} renders as literal {key}
  • Missing values: Render as empty string ""
  • Null/undefined values: Render as empty string ""

Parameter Patterns:

  • Object hash: template(str, {key: value, key2: value2})
  • Array indexing: template(str, [value1, value2])
  • Multiple arguments: template(str, value1, value2, value3)

Important Behavior:

  • Only own properties are accessible (uses hasOwnProperty check)
  • Array prototype methods like splice are not accessible as placeholders
  • Invalid arguments fallback to empty object {}

Usage Examples:

var format = require("string-template");

// Object properties
var result1 = format("User {name} has {role} access", {
    name: "Sarah",
    role: "admin"
});

// Array indices
var result2 = format("Processing {0} of {1} items", [25, 100]);

// Multiple arguments
var result3 = format("Error {0}: {1}", "404", "Not Found");

// Missing values become empty strings
var result4 = format("Hello {name}{suffix}", { name: "World" });
// Result: "Hello World"

// Escaped braces
var result5 = format("Template: {{name}} becomes {name}", { name: "value" });
// Result: "Template: {name} becomes value"

// Array prototype methods are not accessible
var result6 = format("Function{splice}", []);
// Result: "Function" (splice is not accessible)

// Invalid arguments fallback gracefully
var result7 = format("Hello {name}", null);
// Result: "Hello" (null becomes empty object)

Template Compilation

Compiles template strings into reusable functions for improved performance with repeated usage.

/**
 * Compiles a template string into a reusable template function
 * @param {string} string - Template string with {placeholder} syntax
 * @param {boolean} [inline] - If truthy, generates optimized function using new Function
 * @returns {function} Compiled template function accepting single object/array or multiple arguments
 */
function compile(string, inline);

Compilation Modes:

  • Standard compilation: Returns template function using string replacement
  • Inline compilation: Uses new Function for maximum performance optimization

Generated Function Interface:

  • Accepts same parameter patterns as main template function
  • Returns formatted string
  • Can be called with object hash, array, or multiple arguments
  • Non-inline mode: Uses string concatenation (safer, slower)
  • Inline mode: Uses new Function for maximum performance

Usage Examples:

var compile = require("string-template/compile");

// Standard compilation
var greetingTemplate = compile("Hello {0}, you have {1} unread messages");
var greeting1 = greetingTemplate("Robert", 12);
var greeting2 = greetingTemplate("Alice", 3);

// Inline compilation (optimized)
var optimizedTemplate = compile("Welcome {name} to {site}!", true);
var welcome = optimizedTemplate({ name: "John", site: "our website" });

// Array usage with compiled template
var listTemplate = compile("Item {0}: {1}");
var items = ["apple", "banana", "cherry"];
for (var i = 0; i < items.length; i++) {
    console.log(listTemplate(i + 1, items[i]));
}

Error Handling

String Template follows a graceful degradation approach:

  • Missing object properties: Render as empty string
  • Array index out of bounds: Render as empty string
  • Invalid arguments: Fallback to empty object {} when no hasOwnProperty method
  • Null/undefined values: Render as empty string
  • Array prototype access: Blocked by hasOwnProperty check (e.g., splice, length)
  • No exceptions thrown: Functions handle all edge cases gracefully
  • Template compilation errors: Non-inline mode provides safer fallback than inline

Browser Compatibility

  • Internet Explorer 8+: Full support
  • All modern browsers: Full support
  • Node.js: Full support
  • Zero dependencies: No external runtime dependencies
  • Environment agnostic: Works in any JavaScript environment

Performance Notes

  • Template compilation: Pre-processes templates for repeated use
  • Inline compilation: Uses new Function for optimal performance
  • Regex-based replacement: Efficient placeholder matching with /\{([0-9a-zA-Z_]+)\}/g
  • Memory efficient: Minimal overhead for template processing