### Node.js Usage and Component Registration Source: https://context7.com/moappi/json2html/llms.txt Install json2html via npm for server-side rendering. DOM methods are unavailable, but `render()`, `component.add()`, and `version` are accessible. This example demonstrates rendering data and registering a component. ```javascript const json2html = require('node-json2html'); // TypeScript import // import json2html from 'node-json2html'; // const { render, component } = json2html; const data = [ { name: "Bob", fruit: "Bananas" }, { name: "Rick", fruit: "Apples" } ]; const template = { "<>": "div", "text": "${name} likes ${fruit}" }; const html = json2html.render(data, template); // => '
Bob likes Bananas
Rick likes Apples
' // Register a component server-side json2html.component.add("row", { "<>": "tr", "html": [ { "<>": "td", "text": "${name}" }, { "<>": "td", "text": "${fruit}" } ]}); const table = json2html.render(data, { "<>": "table", "html": [{ "[]": "row" }] }); // => '
BobBananas
RickApples
' console.log(json2html.version); // "3.3.3" ``` -------------------------------- ### Render Example Tutorials using json2html Source: https://github.com/moappi/json2html/blob/master/examples/index.html Renders the 'examples' data using the defined 'template' and appends the output to the HTML element with the ID 'tutorials-list'. This demonstrates the core functionality of json2html for dynamic content generation. ```javascript document.getElementById("tutorials-list").json2html(examples,template); ``` -------------------------------- ### Define Example Data for Rendering Source: https://github.com/moappi/json2html/blob/master/examples/index.html An array of objects, where each object represents a tutorial with its name, URL, and description. This data is used as input for the json2html rendering process. ```javascript const examples = [ {"name":"Creating your First Template","url":"simple.html","desc":"Understand how to create a simple tempate that maps data using both shorthand and longhand notation along with some simple logic to toggle the class name of an element"}, {"name":"Add Events","url":"events.html","desc":"Understand how to add events to your templates, like onclick etc.."}, {"name":"Mapping Data & Working with Arrays","url":"arrays.html","desc":"Understand how to map data to your elements plus understand how to work with arrays of literals (instead of objects)"}, {"name":"Creating Tables","url":"tables.html","desc":"Understand how to map data to a table"}, {"name":"Creating Re-Usable Components","url":"components.html","desc":"Understand how to create and register re-usable components"}, {"name":"Using Properties","url":"props.html","desc":"Understand how to pass properties to your shared components"}, {"name":"Using a Wrapper Component","url":"wrapper.html","desc":"Understand how to use a component that can wrap around another template (plus why you would want to do this)"}, {"name":"Using with jQuery","url":"jquery.html","desc":"Understand how to create templates with embedded events that can be used with jQuery"}, {"name":"Understanding Refresh Triggers","url":"refresh.html","desc":"Understand how you can use triggers to help refresh parts of your template without having to re-render again"}, {"name":"Using Input Variable Assignment","url":"assign.html","desc":"Understand how you can attach variables to html input elements that will automatically update when the input changes"} ]; ``` -------------------------------- ### Define json2html Template for Examples Source: https://github.com/moappi/json2html/blob/master/examples/index.html A json2html template object defining the structure and content for rendering the example tutorials. It uses a combination of HTML structure and data mapping to display tutorial names, descriptions, and links. ```javascript const template = {"<>":"div","class":"flex flex-col","html":[ {"<>":"dt","class":"flex items-center gap-x-3 text-base font-semibold leading-7 text-gray-600","html":[ {"<>":"span","text":(o,index)=>{ return( (index+1) + ". " + o.name); }} ]}, {"<>":"dd","class":"mt-4 flex flex-auto flex-col text-base leading-7 text-gray-600","html":[ {"<>":"p","class":"flex-auto","text":"${desc}"}, {"<>":"p","class":"mt-6","html":[ {"<>":"a","href":"${url}","class":"text-sm font-semibold leading-6 text-indigo-600 hover:text-indigo-800","html":[ {"<>":"span","text":"Start "}, {"<>":"span","aria-hidden":"true","html":"→"} ]} ]} ]} ]}; ``` -------------------------------- ### Node.js Usage and `json2html.render` Source: https://context7.com/moappi/json2html/llms.txt Demonstrates how to install and use the json2html package in a Node.js environment. It covers basic HTML rendering from data and templates, as well as registering and using custom components. ```APIDOC ## Node.js Usage Install via npm and `require` the package. The API is identical to the browser version except DOM methods (`Element.prototype.json2html`, jQuery plugin, `json2html.refresh`, `json2html.hydrate`) are unavailable server-side. ```javascript const json2html = require('node-json2html'); // TypeScript import // import json2html from 'node-json2html'; // const { render, component } = json2html; const data = [ { name: "Bob", fruit: "Bananas" }, { name: "Rick", fruit: "Apples" } ]; const template = { "<>": "div", "text": "${name} likes ${fruit}" }; const html = json2html.render(data, template); // => '
Bob likes Bananas
Rick likes Apples
' // Register a component server-side json2html.component.add("row", { "<>": "tr", "html": [ { "<>": "td", "text": "${name}" }, { "<>": "td", "text": "${fruit}" } ]}); const table = json2html.render(data, { "<>": "table", "html": [{ "[]": "row" }] }); // => '
BobBananas
RickApples
' console.log(json2html.version); // "3.3.3" ``` ``` -------------------------------- ### Rendering a Form with JSON to HTML Source: https://github.com/moappi/json2html/blob/master/examples/assign.html The main example demonstrating the conversion of a JSON structure into an HTML form, including radio buttons, checkboxes, and a submit button. ```javascript document.getElementById("root").json2html({"input":{}},form); ``` -------------------------------- ### Render Employee List using json2html Source: https://github.com/moappi/json2html/blob/master/examples/components.html Render a list of employees using the defined templates and components. This example shows how to apply the json2html transformation to an array of employee data. ```javascript document.getElementById("list").json2html(employees, templates.employee); ``` -------------------------------- ### Add Click and Ready Events to List Items Source: https://github.com/moappi/json2html/blob/master/examples/events.html This example shows how to add a button with an onclick event to remove list items and an onready event to display a message when the DOM is ready. It uses data transformation for dynamic styling. ```javascript const employees = [ {"name":"Jenny Brown","role":"CEO","management":true}, {"name":"Ashley White","role":"CFO","management":true}, {"name":"Brandon Green","role":"Graphic Designer"}, {"name":"Sasha Black","role":"Front End Developer"} ]; const template = {"<>":"li","class":"group","html": [ {"<>":"span","class":o=>{ if(o.management) return("text-red-600"); else return("text-pink-600"); },"text":"${name} - ${role}"}, {"<>":"a","class":"ml-5 text-indigo-100 group-hover:text-indigo-800","href":"#","html":"×","title":"remove","onclick":function(e){ e.event.preventDefault(); this.parentNode.remove(); }} ], "onready":function(e){ document.getElementById("ready").classList.remove("hidden"); }}; document.getElementById("list").json2html(employees,template); ``` -------------------------------- ### Map Employee Data with Conditional Styling and Array Rendering Source: https://github.com/moappi/json2html/blob/master/examples/arrays.html This example shows how to map employee data, including conditional styling for management roles and rendering nested access arrays. It utilizes json2html's templating capabilities for dynamic content generation. ```javascript const employees = [ {"name":"Jenny Brown","role":"CEO","management":true,"access":["hr","finance","technical"]}, {"name":"Ashley White","role":"CFO","management":true,"access":["hr","finance"]}, {"name":"Brandon Green","role":"Graphic Designer","access":["technical"]}, {"name":"Sasha Black","role":"Front End Developer","access":["technical"]} ]; const template = {"<>":"li","html": [ {"<>":"span","class":o=>{ if(o.management) return("text-red-600"); else return("text-pink-600"); },"text":"${name} - ${role}"}, {"<>":"ul","class":"ml-5 italic text-gray-500","html":[ {"<>":"li","{}":o=>o.access,"text":"${value}"} ]} ]}; document.getElementById("list").json2html(employees,template); ``` -------------------------------- ### Transform JSON on Node.js with json2html Source: https://github.com/moappi/json2html/blob/master/README.md Use the `transform` method for server-side rendering on Node.js. Ensure you have installed the `node-json2html` package via npm. ```javascript const json2html = require('node-json2html'); let html = json2html.transform([{'name':'Bob','fruit':'Bananas'},{'name':'Rick','fruit':'Apples'}],{"<>":"div","text":"${name} likes ${fruit}"}); ``` -------------------------------- ### Assign Inputs to Variables in json2html Source: https://github.com/moappi/json2html/blob/master/examples/assign.html This example shows how to map form inputs directly to variables. The variable is automatically updated whenever the input value changes. This is useful for creating dynamic forms where input changes trigger immediate variable updates. ```javascript let form = [ { "<>":"div", "html":[ { "<>":"div", "class":"space-y-12", "html":[ { "<>":"div", "class":"border-b border-gray-900/10 pb-12", "html":[ { "<>":"h2", "class":"text-lg font-semibold leading-7 text-gray-900", "text":"Basic Input Types" }, { "<>":"div", "class":"mt-10 grid grid-cols-1 gap-x-6 gap-y-8 sm:grid-cols-6", "html":[ { "<>":"div", "class":"sm:col-span-4", "html":[ { "<>":"label", "for":"text", "class":"block text-sm font-medium leading-6 text-gray-900", "text":"Input Text" }, { "<>":"div", "class":"mt-2", "html":[ { "<>":"div", "class":"flex rounded-md shadow-sm ring-1 ring-inset ring-gray-300 focus-within:ring-2 focus-within:ring-inset focus-within:ring-indigo-600 sm:max-w-md", "html":[ { "<>":"input", "type":"text", "name":"text", "id":"text", "autocomplete":"text", "class":"block flex-1 border-0 bg-transparent py-1.5 pl-1 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6", "placeholder":"Enter text...", ">>" : "input.text" } ] } ] } ] }, { "<>":"div", "class":"sm:col-span-4", "html":[ { "<>":"label", "for":"text", "class":"block text-sm font-medium leading-6 text-gray-900", "text":"Input Number" }, { "<>":"div", "class":"mt-2", "html":[ { "<>":"div", "class":"flex rounded-md shadow-sm ring-1 ring-inset ring-gray-300 focus-within:ring-2 focus-within:ring-inset focus-within:ring-indigo-600 sm:max-w-md", "html":[ { "<>":"input", "type":"number", "name":"number", "id":"number", "class":"block flex-1 border-0 bg-transparent py-1.5 pl-1 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6", "placeholder":"Enter number...", ">>" : "input.number" } ] } ] } ] }, { "<>":"div", "class":"sm:col-span-4", "html":[ { "<>":"label", "for":"text", "class":"block text-sm font-medium leading-6 text-gray-900", "text":"Input Search" }, { "<>":"div", "class":"mt-2", "html":[ { "<>":"div", "class":"flex rounded-md shadow-sm ring-1 ring-inset ring-gray-300 focus-within:ring-2 focus-within:ring-inset focus-within:ring-indigo-600 sm:max-w-md", "html":[ { "<>":"input", "type":"search", "name":"search", "id":"search", "class":"block flex-1 border-0 bg-transparent py-1.5 pl-1 text-gray-900 placeholder:text-gray-400 focus:ring-0 sm:text-sm sm:leading-6", "placeholder":"Enter query...", ">>" : "input.search" } ] } ] } ] }, { "<>":"div", "class":"col-span-full", "html":[ { "<>":"label", "for":"textarea", "class":"block text-sm font-medium leading-6 text-gray-900", "text":"Text Area" }, { "<>":"div", "class":"mt-2", "html":[ { "<>":"textarea", "id":"textarea", "name":"textarea", "rows":"3", "class":"block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6", "placeholder":"Enter some text...", ">>" : "input.textarea" } ] } ] }, { "<>":"div", "class":"sm:col-span-4", "html":[ { "<>":"label", "for":"email", "class":"block text-sm font-medium leading-6 text-gray-900", "text":"Input Email" }, { "<>":"div", "class":"mt-2", "html":[ { "<>":"input", "id":"email", "name":"email", "type":"email", "class":"block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6", ">>" : "input.email" } ] } ] }, { "<>":"div", "class":"sm:col-span-4", "html":[ { "<>":"label", "for":"url", "class":"block text-sm font-medium leading-6 text-gray-900", "text":"Input Url" }, { "<>":"div", "class":"mt-2", "html":[ { "<>":"input", "id":"url", "name":"url", "type":"url", "class":"block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6", ">>" : "input.url" } ] } ] }, { "<>":"div", "class":"sm:col-span-4", "html":[ { "<>":"label", "for":"tel", "class":"block text-sm font-medium leading-6 text-gray-900", "text":"Input Tel" }, { "<>":"div", "class":"mt-2", "html":[ { "<>":"input", "id":"tel", "name":"tel", "type":"tel", "class":"block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6", ">>" : "input.tel" } ] } ] } ] } ] }, { "<>":"div", "class":"space-y-12", "html":[ { "<>":"div", "class":"border-b border-gray-900/10 pb-12", "html":[ { "<>":"h2", "class":"text-lg font-semibold leading-7 text-gray-900", "text":"Special Input Types" }, { "<>":"div", "class":"mt-10 grid grid-cols-1 gap-x-6 gap-y-8 sm:grid-cols-6", "html":[ ] } ] } ] } ] } ] } ]; ``` -------------------------------- ### Render Template with Initial Values Source: https://github.com/moappi/json2html/blob/master/examples/refresh.html This code snippet demonstrates how to render an initial template with specified values and then use json2html to update parts of it. ```javascript let template = [ { "<>": "div", "html": [ { "<>": "h3", "class": "text-base font-semibold leading-6 text-gray-900", "text": "Incremental Counters" }, { "<>": "dl", "class": "mt-5 grid grid-cols-1 gap-5 sm:grid-cols-3", "html": [ { "<>": "div", "class": "overflow-hidden rounded-lg bg-white px-4 py-5 shadow sm:p-6", "html": [ { "<>": "dt", "class": "truncate text-sm font-medium text-gray-500", "text": "Count" }, { "<>": "dd", "#": "number", "class": "mt-1 text-3xl font-semibold tracking-tight text-gray-900", "text": "${number}" } ] }, { "<>": "div", "class": "overflow-hidden rounded-lg bg-white px-4 py-5 shadow sm:p-6", "html": [ { "<>": "dt", "class": "truncate text-sm font-medium text-gray-500", "text": "Multiplier" }, { "<>": "dd", "#": "multiplier", "class": "mt-1 text-3xl font-semibold tracking-tight text-gray-900", "text": "${multiplier}" } ] }, { "<>": "div", "class": "overflow-hidden rounded-lg bg-white px-4 py-5 shadow sm:p-6", "html": [ { "<>": "dt", "class": "truncate text-sm font-medium text-gray-500", "text": "Percentage" }, { "<>": "dd", "#": "percentage", "class": "mt-1 text-3xl font-semibold tracking-tight text-gray-900", "text": "${percentage}%" } ] } ] } ] }, { "<>": "div", "class": "mt-8 flex w-full", "html": [ { "<>": "button", "type": "button", "class": "flex-auto items-center rounded-md bg-indigo-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600", "text": "Increment", "onclick": "e => { //Increment the number e.obj.number++; //Trigger an refresh (should match the event with the # above) json2html.refresh(\"number\"); //Increment the multiplier e.obj.multiplier*=10; //Trigger an update (should match the event with the # above) json2html.refresh(\"multiplier\"); //Increment the percentage e.obj.percentage*=1.1; e.obj.percentage = Math.round(e.obj.percentage,2); //Trigger an update (should match the event with the # above) json2html.refresh(\"percentage\"); }" }, { "<>": "button", "type": "button", "class": "ml-3 flex-auto items-center rounded-md bg-pink-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-pink-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600", "text": "Decrement", "onclick": "e => { //Increment the number e.obj.number--; //Trigger an refresh (should match the event with the # above) json2html.refresh(\"number\"); //Increment the multiplier e.obj.multiplier/=10; //Trigger an refresh (should match the event with the # above) json2html.refresh(\"multiplier\"); //Increment the percentage e.obj.percentage/=1.1; e.obj.percentage = Math.round(e.obj.percentage,2); //Trigger an refresh (should match the event with the # above) json2html.refresh(\"percentage\"); }" } ] } ]; //Render the template with the initial values document.getElementById("root").json2html({"number":1,"multiplier":10,"percentage":10},template); ``` -------------------------------- ### Register Components with json2html Source: https://github.com/moappi/json2html/blob/master/examples/wrapper.html Register multiple components, including a page wrapper with header and footer, and nested employee details. This allows for reusable UI elements defined in JSON. ```javascript json2html.component.add({ "page":[ {"<>":"div","class":"px-6 py-24 sm:px-6 sm:py-32 lg:px-8","html":[ {"<>":"div","class":"mx-auto max-w-2xl text-center","html":[ {"<>":"h2","class":"text-3xl font-bold tracking-tight text-gray-900 sm:text-4xl","text":"${title}"}, {"<>":"p","class":"mt-6 max-w-xl text-lg leading-8 text-gray-600","text":"${desc}"}, {"<>":"p","class":"mt-6 italic","html":"For a more comprehensive framework for application using json2html check out the j2h framework, it helps manage your json2html pages and components and is similar to react, plus it works with node.js and on the browser."}, {"<>":"p","class":"mt-6 max-w-xl text-base leading-8 text-gray-400","text":"Right click and 'View page source' to see how this page was rendered."} ]}, {"<>":"div","class":"mx-auto mt-16 max-w-2xl sm:mt-20 lg:mt-24 lg:max-w-4xl border rounded p-10","html":[ {"html":(o,index,data,html)=>html} ]} ]} ], "employee":{ "<>":"li", "html": [ {"[ ]":"employee/name"}, {"<>":"div","class":"ml-5","html":[ {"[ ]":"employee/access"}, {"[ ]":"employee/payments"} ]} ] }, "employee/name":{ "<>":"div", "class":o=>{ if(o.management) return("text-red-600"); else return("text-pink-600"); }, "text":"${name} - ${role}" }, "employee/access":{ "<>":"div", "html":[ {"<>":"span","class":"font-gray-800","text":"Access - "}, {"<>":"ul","class":"italic text-gray-500 space-x-1 inline-block","html":[ {"<>":"li","class":"inline-block","{}":o=>o.access,"text":"${value}"} ]} ] }, "employee/payments":{ "<>":"div", "html":[ {"<>":"div","class":"font-gray-800","text":"Payments Received"}, {"<>":"ul","class":"italic text-gray-500","html":[ {"[ ]":"employee/payment","{}":o=>o.payments} ]} ] }, "employee/payment":{ "<>":"li", "class":"ml-5", "text":"${amount} (${date})" } }); ``` -------------------------------- ### Register Employee Components with json2html Source: https://github.com/moappi/json2html/blob/master/examples/components.html Register multiple reusable components for employee data, including name, role, access, and payments. Components can be registered individually or as a group. ```javascript const employees = [ { "name": "Jenny Brown", "role": "CEO", "management": true, "access": ["hr", "finance", "technical"], "payments": [ {"date": "Today", "amount": "$4,500"}, {"date": "Last Week", "amount": "$4,500"}, {"date": "2 Weeks Ago", "amount": "$3,500"} ] }, { "name": "Ashley White", "role": "CFO", "management": true, "access": ["hr", "finance"], "payments": [ {"date": "Yesterday", "amount": "$3,500"}, {"date": "Last Week", "amount": "$3,500"}, {"date": "2 Weeks Ago", "amount": "$2,500"} ] }, { "name": "Brandon Green", "role": "Graphic Designer", "access": ["technical"], "payments": [ {"date": "Today", "amount": "$2,500"}, {"date": "Last Week", "amount": "$2,500"} ] }, { "name": "Sasha Black", "role": "Front End Developer", "access": ["technical"], "payments": [ {"date": "Yesterday", "amount": "$2,500"} ] } ]; json2html.component.add({ "employee/name": {"<>": "div", "class": o => { if (o.management) return ("text-red-600"); else return ("text-pink-600"); }, "text": "${name} - ${role}"}, "employee/access": {"<>": "div", "html": [ {"<>": "span", "class": "font-gray-800", "text": "Access - "}, {"<>": "ul", "class": "italic text-gray-500 space-x-1 inline-block", "html": [ {"<>": "li", "class": "inline-block", "{}": o => o.access, "text": "${value}"} ]} ]}, "employee/payments": {"<>": "div", "html": [ {"<>": "div", "class": "font-gray-800", "text": "Payments Received"}, {"<>": "ul", "class": "italic text-gray-500", "html": [ {"[\]": "employee/payment", "{}": o => o.payments} ]} ]}, "employee/payment": {"<>": "li", "class": "ml-5", "text": "${amount} (${date})"} }); ``` -------------------------------- ### Registering Components with json2html Source: https://github.com/moappi/json2html/blob/master/examples/props.html Register multiple components at once using an object. Individual components can also be registered using json2html.component.add(name, template). ```javascript const employees = [ {"name":"Jenny Brown","role":"CEO","management":true,"access":["hr","finance","technical"],"payments":[{"date":"Today","amount":"$4,500"},{"date":"Last Week","amount":"$4,500"},{"date":"2 Weeks Ago","amount":"$3,500"}]}, {"name":"Ashley White","role":"CFO","management":true,"access":["hr","finance"],"payments":[{"date":"Yesterday","amount":"$3,500"},{"date":"Last Week","amount":"$3,500"},{"date":"2 Weeks Ago","amount":"$2,500"}]}, {"name":"Brandon Green","role":"Graphic Designer","access":["technical"],"payments":[{"date":"Today","amount":"$2,500"},{"date":"Last Week","amount":"$2,500"}]}, {"name":"Sasha Black","role":"Front End Developer","access":["technical"],"payments":[{"date":"Yesterday","amount":"$2,500"}]} ]; json2html.component.add({ //Employee name (and role) Component "employee/name":{"<>":"div","class":(o,i,p)=>{ console.log("PROPS",JSON.stringify(p)); if(o.management) return("text-" + p.color.management); return("text-" + p.color.employee); },"text":"${name} - ${role}"}, //Employee access Component (lists all access inline) "employee/access":{"<>":"div","html": [ {"<>":"div","class":"font-gray-800","text":(o,i,p)=>p.title}, {"<>":"ul","class":"italic text-gray-500 space-x-1 inline-block pl-5","html": [ {"<>":"li","class":"inline-block","{}":o=>o.access,"text":"${value}"} ]} ]}, //Employee Payments "employee/payments":{"<>":"div","html": [ {"<>":"div","class":"font-gray-800","text":(o,i,p)=>p.title}, {"<>":"ul","class":"italic text-gray-500 pl-5","html": [ {"<>":"li","class":"inline-block","{}":o=>o.payments,"text":"${amount} (${date})"} ]} ]}, //Employee payment list item "employee/payment":{"<>":"li","text":"${amount} (${date})"} }); ``` -------------------------------- ### DOM Rendering with Event Hydration Source: https://context7.com/moappi/json2html/llms.txt Renders a template against data and inserts the result into a live DOM element, automatically attaching all event handlers. Supports 'append' (default), 'prepend', and 'replace' methods. Use this for templates with 'on*' event handlers or '#'/onready refresh triggers. ```html ``` -------------------------------- ### Rendering Employee List with json2html Source: https://github.com/moappi/json2html/blob/master/examples/props.html Render the list of employees using the defined template. This can be done using jQuery or directly with json2html.render if no events are involved. ```javascript document.getElementById("list").json2html(employees,templates.employee); ``` -------------------------------- ### Element.prototype.json2html Source: https://context7.com/moappi/json2html/llms.txt Renders a template against data and inserts the result into a live DOM element, automatically attaching all event handlers. Supports 'append' (default), 'prepend', and 'replace' methods. ```APIDOC ## Element.prototype.json2html(obj, template [, options]) Browser-only. Renders a template against data and inserts the result into a live DOM element, automatically attaching all event handlers defined in the template. Supports `method: "append"` (default), `"prepend"`, and `"replace"`. This is the preferred method when templates contain `on*` event handlers or `onready` / `#` refresh triggers. ### Parameters - **obj** (Object|Array) - The data object or array to render. - **template** (Object|Array) - The template object or array to render against. - **options** (Object) - Optional configuration object. - **method** (String) - The rendering method: "append" (default), "prepend", or "replace". ### Example ```html ``` ``` -------------------------------- ### Define Page Template Source: https://github.com/moappi/json2html/blob/master/examples/wrapper.html Define the main page template using json2html's structure, referencing the 'page' component. This template includes a header with title and description, and a content area where dynamic data will be rendered. ```javascript const template = [ { "<>": "page", "title": "Employee List", "desc": "A list of employees and their details.", "html": [ { "<>": "employee", "obj": "employees" } ] } ]; ``` -------------------------------- ### Manual hydration with `json2html.hydrate` Source: https://context7.com/moappi/json2html/llms.txt The `json2html.hydrate` function attaches events and refresh triggers to existing DOM elements, enabling server-side rendering (SSR) workflows. This allows for interactive UIs where HTML is rendered on the server, and the client only needs to wire up interactivity without a full re-render. ```APIDOC ## `json2html.hydrate(parent, events, triggers)` — Manually hydrate server-rendered HTML Attaches events and refresh triggers to already-existing DOM elements, enabling server-side rendering (SSR) workflows where HTML is generated with `json2html.render()` on the server and the client only needs to wire up interactivity. `events` and `triggers` come from the `.toJSON()` output of an iHTML object. ```javascript // --- Server side (Node.js) --- const json2html = require('node-json2html'); const template = { "<>": "button", "text": "Click me", "onclick": e => console.log("clicked", e.obj.label) }; const data = { label: "Hello" }; // Render to iHTML to capture events const ihtml = json2html.render(data, template, { output: "ihtml" }); // ihtml.html => '' // ihtml.events => { abc123: { type: "click", data: {...}, action: fn } } // Send ihtml.html to client; ship ihtml.toJSON() as JSON for hydration // --- Client side (Browser) --- // Assume #container has the server-rendered HTML already in the DOM const container = document.getElementById("container"); const { events, triggers } = serverRenderedJSON; // received from server json2html.hydrate(container, events, triggers); // Now the button's onclick is live without re-rendering the HTML ``` ``` -------------------------------- ### Form Submission with JSON Data Source: https://github.com/moappi/json2html/blob/master/examples/assign.html Shows how to attach a submit button that, when clicked, displays the JSON object associated with the form event. ```javascript {"<>":"button","type":"submit","class":"rounded-md bg-indigo-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600","text":"View Input Variables","onclick":function(e){ alert(JSON.stringify(e.obj)); }} ``` -------------------------------- ### Defining a Template for Employee Rendering Source: https://github.com/moappi/json2html/blob/master/examples/props.html Define a template to render an employee object, utilizing previously registered components for name, access, and payments. The entire employee object is passed to each component, allowing access to its properties. ```javascript const templates = { //Template to render an employee "employee":{"<>":"li","html": [ //Output the employee name {"<>":"div","class":"font-medium","html":[ {"<>":"employee/name","color":{"management":"red-600","employee":"blue-600"}} ]}, //Employee Access {"<>":"div","class":"ml-5","html":[ {"<>":"employee/access","title":"Employee Access"} ]}, //Employee Payments {"<>":"div","class":"ml-5","html":[ {"<>":"employee/payments","title":"Payments Received"} ]} ]} }; ``` -------------------------------- ### Nested Arrays with Sub-object Scope Source: https://context7.com/moappi/json2html/llms.txt Demonstrates rendering nested arrays by combining the '{}' key for scope and multiple levels of 'html' arrays in the template. ```javascript // --- Nested arrays with {} --- json2html.render( { departments: [{ name: "Eng", members: ["Alice", "Bob"] }] }, { "<>": "ul", "html": [{ "<>": "li", "{}": o => o.departments, "html": [ { "<>": "h1", "html": "${name}" }, { "<>": "span", "{}": o => o.members, "html": "${value}" } ] }] } ); // => '' ``` -------------------------------- ### Block Container Rendering Source: https://context7.com/moappi/json2html/llms.txt Renders content without a wrapper element by using the 'html' key directly. This is useful for inserting fragments of HTML. ```javascript // --- Block container (no wrapper element) --- json2html.render( { name: "Ashley" }, { "html": "

${name}

" } ); // => '

Ashley

' ``` -------------------------------- ### Register Reusable Components with json2html Source: https://context7.com/moappi/json2html/llms.txt Register single or multiple named templates as globally reusable components. Components can be invoked using the `[]` key and receive the data object. Props can be passed at the call site. ```javascript // Register a single component json2html.component.add("badge", { "<>": "span", "class": "badge", "text": "${label}" }); // Register multiple components at once json2html.component.add({ "employee/name": { "<>": "div", "class": o => o.management ? "text-red-600" : "text-blue-600", "text": "${name} - ${role}" }, "employee/payment": { "<>": "li", "text": "${amount} (${date})" }, "employee/payments": { "<>": "div", "html": [ { "<>": "h4", "text": "Payments" }, { "<>": "ul", "html": [ { "[]": "employee/payment", "{}": o => o.payments } ]} ] } }); // Use components via the [] key const result = json2html.render( [ { name: "Jenny Brown", role: "CEO", management: true, payments: [{ date: "Today", amount: "$4,500" }] }, { name: "Sasha Black", role: "Developer", management: false, payments: [{ date: "Yesterday", amount: "$2,500" }] } ], { "<>": "li", "html": [ { "[]": "employee/name" }, { "[]": "employee/payments" } ] } ); // => '
  • Jenny Brown - CEO
    //

    Payments

  • //
  • Sasha Black - Developer
    ...
  • ' // Retrieve a registered component template const tpl = json2html.component.get("employee/name"); ``` -------------------------------- ### Nested Child Templates with json2html Source: https://context7.com/moappi/json2html/llms.txt Demonstrates rendering nested JSON structures using an array of child templates. Conditional styling is applied using an inline function. ```javascript // --- Nested child templates --- json2html.render( [ { name: "Jenny Brown", role: "CEO", management: true }, { name: "Sasha Black", role: "Developer", management: false } ], { "<>": "li", "html": [ { "<>": "span", "class": o => o.management ? "text-red-600" : "text-pink-600", "text": "${name} - ${role}" } ] } ); // => '
  • Jenny Brown - CEO
  • //
  • Sasha Black - Developer
  • ' ``` -------------------------------- ### Assigning Checkbox Values Source: https://github.com/moappi/json2html/blob/master/examples/assign.html Illustrates assigning values to checkbox inputs using the '>>' operator for element selection. ```javascript {"<>":"div","class":"flex items-center gap-x-3","html":[{"<>":"input","name":"checkbox","type":"checkbox","class":"h-4 w-4 border-gray-300 text-indigo-600 focus:ring-indigo-600",">>":"input.checkbox.canada"},{"<>":"label","class":"block text-sm font-medium leading-6 text-gray-900","text":"Canada"}]} ```