Ad

Writing Code In A For Loop

- 1 answer

I am currently writing a JSON result onto a page using a for loop similar to the below example (simplified version):

var output = "";
for (i in response) {
    var ID = response[i].ID
    var name = response[i].name

    output += "<div id=\""+ID+"\">"+name+"</div>"
}

$("#allResults").html(output);

The output variable has become bloated & confusing. Is there any way to write to the output variable without needing "" as it is particularly hard to insert variables & later modify the code?

Ad

Answer

Try the below HandlebarJS Templating Snippet. Include this:

<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.js"></script>

Handlebar Template:

<script id="name-template" type="text/x-handlebars-template">
  {{#each people}}
    <div id="{{ID}}">{{name}}.</div>
  {{/each}}
</script>

HTML:

<div class="content-placeholder"></div>

jQuery and Template Compilation:

$(function () {
  // Grab the template script
  var theTemplateScript = $("#name-template").html();

  // Compile the template
  var theTemplate = Handlebars.compile(theTemplateScript);

  // This is the default context, which is passed to the template
  var context = {
    people: [ 
      { ID: 1000, name: 'Simpson' },
      { ID: 1001, name: 'Griffin' },
      { ID: 1002, name: 'Cartman' },
      { ID: 1003, name: 'McCormick' }
    ]
  };

  // Pass our data to the template
  var theCompiledHtml = theTemplate(context);

  // Add the compiled html to the page
  $('.content-placeholder').append(theCompiledHtml);
});
Ad
source: stackoverflow.com
Ad