toy
toy

Reputation: 12141

Javascript, jQuery pattern to create HTML document

I'm not sure if I'm asking the right question or not. But my application heavily relies on Javascript and jQuery to create HTML document. So I have a lot of this "jQuery(") and then a lot of div.attr("id","123").

So, is there a better way to do this, or some design pattern to deal with this?

Thanks a lot.

Upvotes: 2

Views: 660

Answers (1)

amosrivera
amosrivera

Reputation: 26514

Yes, jQuery Templates. They make it easier to build html with jQuery, you can do:

<script id="movieTemplate" type="text/x-jquery-tmpl"> 
    <li><b>${Name}</b> (${ReleaseYear})</li>
</script>

<ul id="movieList"></ul>

<script>
var movies = [
    { Name: "The Red Violin", ReleaseYear: "1998" },
    { Name: "Eyes Wide Shut", ReleaseYear: "1999" },
    { Name: "The Inheritance", ReleaseYear: "1976" }
];

/* Render the template with the movies data and insert
   the rendered HTML under the "movieList" element */
$( "#movieTemplate" ).tmpl( movies )
    .appendTo( "#movieList" );
</script>

And get:

  • The Red Violin (1998)
  • Eyes Wide Shut (1999)
  • The Inheritance (1976)

Upvotes: 3

Related Questions