Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's a clean and efficient way to generate and append HTML with JavaScript or JQuery?

I was going to ask this question (until I found it was already asked) and now have the answer to that question:

It's better to request JSON from a PHP script and then wrap the results in HTML with JavaScript.

Now I have the unfortunate task of generating HTML with JavaScript to append to my document and am not sure how best to approach this.

With PHP I could simply store a HTML file and then use file_get_contents() and regex to replace some tokens with the relevant information, however I don't think it's that easy with JavaScript.

Some methods I have thought of:

  1. The repulsive approach. Generate a massive ugly string and then append that:

    var html = '<div class="comment">' +
        '<strong>' + author + '</strong>: ' +
        '<p>' + content + '</p>' +
    '</div>';
    
    $("#comments").append(html);
    
  2. Store the string somewhere and then use regex on that, which might look like this:

    var commentHTML = '<div class="cmt"><strong>{auth}</strong>: {cmt}</div>';
    

Is there a library/plugin that deals with this better maybe? Riddling my JavaScript with chunks of HTML stored in strings is something I'd really like to avoid. Maybe there is a similar method to what I mentioned I do using PHP? Can JavaScript read HTML files and store the content as a string?

like image 410
Marty Avatar asked Feb 21 '23 20:02

Marty


1 Answers

Congrats, you just invented Mustache.js. Check it out: https://github.com/janl/mustache.js

var data = { author: "An Author", content: "Some content" };
var template = "<div class='cmt'><strong>{{author}}</strong>: {{comment}</div>";
var html = Mustache.render(template, data);
like image 176
McGarnagle Avatar answered Feb 23 '23 15:02

McGarnagle