node-json2html
Version:
json2html - HTML templating in pure javascript
75 lines (56 loc) • 2.86 kB
HTML
<html>
<head>
<title>json2html - Data Mapping & Array 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">Mapping Data & Working with Arrays</h2>
<p class="mx-auto mt-6 max-w-xl text-lg leading-8 text-gray-600">Understand how to map data to your elements plus understand how to work with arrays of literals (instead of objects).</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>
<!-- Tutorials -->
<div class="mx-auto mt-16 max-w-2xl sm:mt-20 lg:mt-24 lg:max-w-4xl border rounded p-10">
<ul id="list" class="space-y-5"></ul>
</div>
</div>
</div>
</body>
<script>
//In this example we'll show you how you can map data directly to a template
// plus show you how to work with arrays of literals (like strings) instead of objects
//Data that we want to render
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"]}
];
//Templates that we want to use
const template = {"<>":"li","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}"},
//List the access that each employee has
{"<>":"ul","class":"ml-5 italic text-gray-500","html":[
//We can list all the access by simply mapping the access array (using the reserved {} attribute) to the li element
// this will repeat an li element for every value in the array
// NOTE the {} reserved attribute needs to be a function that returns the data you wish to map
// this also works for components! But we'll get to this later
{"<>":"li","{}":o=>o.access,"text":"${value}"}
]}
]};
//Render the list of employees using jquery
// note we can also do this using json2html.render as we don't have any events
document.getElementById("list").json2html(employees,template);
</script>
</html>