HTML templating in pure javascript that transforms JSON objects into HTML using JavaScript template objects
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Core template rendering functionality that transforms JSON data into HTML using JavaScript template objects with support for embedded events, string interpolation, and complex data structures.
Transforms JSON objects into HTML using template objects with JavaScript-based template syntax.
/**
* Renders JSON object to HTML string using template
* @param {object|string|array} obj - JSON object, array, or JSON string to render
* @param {object|array} template - json2html template (object/array/JSON string)
* @param {object} [options] - Optional configuration
* @param {object} [options.props] - Properties for template rendering (accessible via @property)
* @param {object} [options.components] - Local component definitions (name:template pairs)
* @param {string} [options.output="html"] - Output type: "html" (string) or "ihtml" (object)
* @returns {string|iHTML} Rendered HTML string or iHTML object based on output option
*/
function render(obj, template, options);Usage Examples:
const json2html = require('node-json2html');
// Simple object rendering
const user = { name: "Alice", age: 30 };
const template = { "<>": "div", "text": "Name: ${name}, Age: ${age}" };
const html = json2html.render(user, template);
// Result: <div>Name: Alice, Age: 30</div>
// Array rendering
const users = [
{ name: "Alice", age: 30 },
{ name: "Bob", age: 25 }
];
const listTemplate = { "<>": "li", "text": "${name} (${age})" };
const html = json2html.render(users, listTemplate);
// Result: <li>Alice (30)</li><li>Bob (25)</li>
// Complex nested templates
const complexTemplate = {
"<>": "div",
"class": "user-card",
"html": [
{ "<>": "h2", "text": "${name}" },
{ "<>": "p", "text": "Age: ${age}" },
{ "<>": "button", "text": "Edit", "onclick": function(e) { alert("Edit " + this.name); } }
]
};
// Using properties
const propsTemplate = { "<>": "div", "text": "${name} - ${@title}" };
const html = json2html.render(
{ name: "Alice" },
propsTemplate,
{ props: { title: "Administrator" } }
);
// Result: <div>Alice - Administrator</div>json2html uses a JavaScript object-based template syntax with special properties:
/**
* Template object structure with special properties
*/
interface Template {
/** HTML element tag name */
"<>"?: string;
/** Object or function for data transformation */
"{}"?: object | function;
/** Component reference by name */
"[]"?: string;
/** Text content (HTML-encoded) */
"text"?: string | function;
/** HTML content (raw or nested templates) */
"html"?: string | function | object[];
/** Two-way data binding for form elements */
">>"?: string;
/** Refresh/update trigger ID */
"#"?: string;
/** Event handlers (onclick, onchange, etc.) */
[key: `on${string}`]: function;
/** Standard HTML attributes */
[attribute: string]: any;
}Template Property Examples:
// HTML element with attributes
{ "<>": "div", "class": "container", "id": "main" }
// Result: <div class="container" id="main"></div>
// Text content (HTML-encoded)
{ "<>": "p", "text": "${message}" }
// Input: { message: "<script>alert('xss')</script>" }
// Result: <p><script>alert('xss')</script></p>
// HTML content (raw)
{ "<>": "div", "html": "<strong>Bold text</strong>" }
// Result: <div><strong>Bold text</strong></div>
// Nested templates
{
"<>": "article",
"html": [
{ "<>": "h1", "text": "${title}" },
{ "<>": "p", "text": "${content}" }
]
}
// Event handlers
{
"<>": "button",
"text": "Click me",
"onclick": function(e) {
console.log("Button clicked!", this, e);
}
}
// Two-way data binding
{
"<>": "input",
"type": "text",
"value": "${name}",
">>": "name" // Updates the name property when input changes
}
// Component reference
{ "[]": "user-card", "user": "${.}", "theme": "dark" }Template strings support ${path} syntax for accessing object properties and array indices:
/**
* String interpolation patterns
*/
// Object property access
"${name}" // obj.name
"${user.name}" // obj.user.name
"${user.address.city}" // obj.user.address.city
// Array access patterns
"${0}" // array[0] (for literal arrays)
"${items.0.name}" // obj.items[0].name
// Properties access (prefix with @)
"${@theme}" // options.props.theme
"${@config.mode}" // options.props.config.mode
// Special values for literal arrays
"${value}" // The literal value when rendering arrays of primitives
"${index}" // The current array indexInterpolation Examples:
// Object property interpolation
const data = {
user: {
name: "Alice",
profile: { city: "New York" }
}
};
const template = { "<>": "span", "text": "${user.name} from ${user.profile.city}" };
// Result: <span>Alice from New York</span>
// Array literal rendering
const numbers = [1, 2, 3];
const template = { "<>": "li", "text": "Item ${index}: ${value}" };
// Result: <li>Item 0: 1</li><li>Item 1: 2</li><li>Item 2: 3</li>
// Properties interpolation
const template = { "<>": "div", "class": "${@theme}-container" };
const html = json2html.render({}, template, { props: { theme: "dark" } });
// Result: <div class="dark-container"></div>Templates support JavaScript functions for dynamic content generation and data transformation:
/**
* Function-based template properties
* @param {object} obj - Current data object being rendered
* @param {number} index - Current array index (if rendering array)
* @param {object} props - Properties object from options.props
* @param {string} [html] - Inner HTML content (for html property functions)
* @returns {any} Value to use for the template property
*/
function templateFunction(obj, index, props, html);Function Examples:
// Dynamic text generation
const template = {
"<>": "div",
"text": function(obj, index, props) {
return `User ${obj.name} is ${obj.age >= 18 ? 'adult' : 'minor'}`;
}
};
// Dynamic HTML generation
const template = {
"<>": "div",
"html": function(obj, index, props) {
if (obj.isAdmin) {
return [
{ "<>": "h2", "text": "Admin: ${name}" },
{ "<>": "button", "text": "Admin Panel" }
];
}
return { "<>": "span", "text": "${name}" };
}
};
// Data transformation with {} property
const template = {
"{}": function(obj, index, props) {
return {
...obj,
displayName: `${obj.firstName} ${obj.lastName}`,
isActive: obj.status === 'active'
};
},
"<>": "div",
"text": "${displayName} (${isActive})"
};The render function supports two output modes controlled by the options.output parameter:
// HTML string output (default)
const html = json2html.render(data, template);
// Returns: string
// iHTML object output (for browser usage with events)
const ihtml = json2html.render(data, template, { output: "ihtml" });
// Returns: iHTML object with html, events, and triggers propertiesiHTML Output Example:
const template = {
"<>": "button",
"text": "Click me",
"onclick": function(e) { alert("Clicked!"); }
};
const ihtml = json2html.render({}, template, { output: "ihtml" });
console.log(ihtml.html); // "<button>Click me</button>"
console.log(ihtml.events); // { "randomId": { type: "click", action: function... } }
console.log(ihtml.triggers); // {}