Ad
Writing Code In A For Loop
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
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad