UNPKG

node-json2html

Version:

json2html - HTML templating in pure javascript

89 lines (64 loc) 3.2 kB
<!DOCTYPE html> <html> <head> <title>json2html - Events Tutorial</title> <!-- Tailwind CSS --> <script src="https://cdn.tailwindcss.com"></script> <!-- json2html --> <script src="../json2html.js"></script> </head> <body> <div class="px-6 py-24 sm:px-6 sm:py-32 lg:px-8"> <!-- Header --> <div class="mx-auto max-w-2xl text-center"> <h2 class="text-3xl font-bold tracking-tight text-gray-900 sm:text-4xl">Adding Events to your Templates</h2> <p class="mx-auto mt-6 max-w-xl text-lg leading-8 text-gray-600">Understand how to add events to your templates like onclick and onready etc..</p> <p class="mx-auto mt-6 max-w-xl text-base leading-8 text-gray-400">Right click and 'View page source' to see how this page was rendered.</p> </div> <!-- Show that we're ready --> <!-- Tutorials --> <div class="mx-auto mt-16 max-w-2xl sm:mt-20 lg:mt-24 lg:max-w-4xl border rounded p-10"> <span id="ready" class="inline-flex items-center rounded-md bg-green-50 px-2 py-1 text-xs font-medium text-green-700 ring-1 ring-inset ring-green-600/20 float-right">READY</span> <ul id="list"></ul> </div> </div> </div> </body> <script> //In this example we'll use the same list of employees but add a button were can can remove them from the list //Data that we want to render 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"} ]; //Template we'll use to render these employees const template = {"<>":"li","class":"group","html": [ //Span element with special logic for the class property {"<>":"span","class":o=>{ //If the user is part of managemnt then put them in blue if(o.management) return("text-red-600"); else return("text-pink-600"); },"text":"${name} - ${role}"}, //Add a button to remove this employee from the list // not a great idea using an inline style, but shows that we can add any property to the DOM element {"<>":"a","class":"ml-5 text-indigo-100 group-hover:text-indigo-800","href":"#","html":"&times;","title":"remove","onclick":function(e){ //e.event => js event //e.obj => object we're rendering //e.data => data object we can optional assign during the render call //Stop the link from navigating away // example of how can can acces the jquery event e.event.preventDefault(); //Access this element's parent (the top level li element) // then remove it this.parentNode.remove(); }} ],"onready":function(e){ //Show the ready message once the dom is ready with the rendered template // onready is an event that's unique to json2html document.getElementById("ready").classList.remove("hidden"); }}; document.getElementById("list").json2html(employees,template); </script> </html>