Get Programming with JavaScript - Listing 19.07

Listing 19.07 - A function to fill templates with data

function fill (template, data) { Object.keys(data).forEach(function (key) { var placeholder = "{{" + key + "}}"; var value = data[key]; while (template.indexOf(placeholder) !== -1) { template = template.replace(placeholder, value); } }); return template; } // Test the fill function var data = { title: "Fitness App v1.0 Live!", body: "Yes, version 1 is here...", posted: "October 3rd, 2016", author: "Oskar", social: "@appOskar51" }; var templateScript = document.getElementById("newsItemTemplate"); var templateString = templateScript.innerHTML; var newsContainer = document.getElementById("news"); newsContainer.innerHTML = fill(templateString, data);

Further Adventures

Listing 19.07 - A function to fill templates with data - Tasks 1 & 2

JS

function fill (template, data) { Object.keys(data).forEach(function (key) { var placeholder = "{{" + key + "}}"; var value = data[key]; while (template.indexOf(placeholder) !== -1) { template = template.replace(placeholder, value); } }); return template; } // Test the fill function var data = { title: "Fitness App v1.0 Live!", body: "Yes, version 1 is here...", posted: "October 3rd, 2016", firstName: "Oskar", lastName: "Smith", social: "@appOskar51" }; var templateScript = document.getElementById("newsItemTemplate"); var templateString = templateScript.innerHTML; var newsContainer = document.getElementById("news"); newsContainer.innerHTML = fill(templateString, data);

HTML

<script type="text/template" id="newsItemTemplate"> <div class="newsItem"> <h3>{{title}}<span> - by {{firstName}} {{lastName}}</span></h3> <p>{{body}}</p> <p class="posted"><em>Posted: {{posted}}</em></p> <p class="follow">Follow {{firstName}} {{lastName}} {{social}}</p> </div> </script>