node-json2html Documentation

repository·master·Indexed 20 days ago

https://github.com/moappi/json2html

A JavaScript library for HTML templating that renders JSON objects into HTML. It supports both client-side and Node.js environments, allows for embedded interactive events, and provides methods such as render() and transform() to convert data arrays and template objects into HTML strings.

Tokens
568
Snippets
5
Records
5
Agent score
21%

What's inside node-json2html

  1. Embed interactive events in templates

    master

    You can embed JavaScript event handlers directly within your templates. This allows you to define interactions (like onclick) inside the JSON template rather than attaching them manually after rendering. This works seamlessly with jQuery.

    // Example of an embedded onclick event
    {"<>":"button","text":"Click Me","onclick":(e)=>{
    	alert("You just clicked this");
    }};
  2. Use json2html in Node.js

    master

    In a Node.js environment, require the module and use the transform method to convert JSON data into an HTML string.

    const json2html = require('node-json2html');
    
    let html = json2html.transform(
        [{'name':'Bob','fruit':'Bananas'},{'name':'Rick','fruit':'Apples'}],
        {"<>":"div","text":"${name} likes ${fruit}"}
    );
  3. Render JSON objects into HTML with json2html.render()

    master

    The render method takes a data array and a template object to produce HTML. The template uses special keys like <> to define the HTML tag and ${key} syntax to inject data from the JSON objects.

    Example of rendering a list of people:

    json2html.render(
        [
            {"name": "Sasha", "age":27},
            {"name": "Bobby", "age":45}
        ], 
        {"<>": "li", "html":[
        	{"<>": "span", "text": "${name} (${age} years old)"}
          ]}
    );
  4. Import json2html in TypeScript

    master

    When using TypeScript, you can import the module and destructure specific methods like render and component from the default export.

    import json2html from 'node-json2html';
    const { render, component } = json2html;