0

I've been doing a lot of googling and looking for the best way to dynamically generate html. My current solution follows in code snippets. The idea of my code is to grab data from the server and then use the returned array of task items to build dynamic list content.

My question is, surely there is a better, less verbose and more maintainable way of doing this?

// returns an array of task objects from server
$.post("/fetch", JSON.stringify({
    "Sort": "tasksperuser"
  }), function(data) {
    // Generate a task line item in html before appending for each task object.
    $.each(data, function() {
      console.log($(this));
      $("#taskBox").append(taskline);
      var tempkey = $(this)[0]['key'];
      $("#taskBox > p:last").attr("id", tempkey);
      if ($(this)[0]['completed'] == true) {
        $("#" + tempkey + " .taskCheckbox").prop('checked', true)
          .siblings('.task-title').css("text-decoration", "line-through");
      }
      $("#" + tempkey + " .task-title").text($(this)[0]['title']);
    })
  }, "json")
  .fail(function() {
    console.log("Tasks load per user from server failure.");
  });

var taskline = '<p id="" class="taskWrapper">' +
  '<input type="checkbox" class="taskCheckbox"/>' +
  '<span class="task-title"></span>' +
  '<button type="button" class="btn btn-default btn-xs taskDelete pull-right" aria-label="Left Align">' +
  '  <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>' +
  '</button>' +
  '<button type="button" class="btn btn-default btn-xs pull-right" data-toggle="modal" data-target="#TaskModal" data-key="" aria-label="Left Align">' +
  '  <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>' +
  '</button>' +
  '</p>'

2
  • You can abstract some of this code... like instead of having all of that code inside of the each loop, you could create a new function called newTaskLine(param1, param2, param3); That would clean up that loop pretty substantially and be a lot easier to maintain. For making it less verbose/easier, you can do something like document.createElement('input') and then set the attributes on that element, requires less work IMO, but optional Commented Mar 29, 2015 at 6:54
  • Great thanks! I'll use this as the short term solution but will likely have to use a templating engine as suggested by @josephthedreamer Commented Mar 29, 2015 at 8:28

1 Answer 1

1

Use a templating engine like Mustache or Handlebars. You can inject "mustaches" into the template and name them accordingly in the passed data. This removes the need to traverse the DOM of your newly created HTML to inject values.

Sign up to request clarification or add additional context in comments.

1 Comment

Went with Dust.js in the end. Waaay better than my code above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.