jQFragment

jQFragment is a very lightweight (540 bytes!) script for extracting HTML template fragments from the DOM, eliminating the need for messy element generation inside your javascript functions.

jQFragment was inspired by James Padosley's JSHTML script.

jQFragment is a bit different, though:

  1. You can't change delimiters; {{ and }} are what you get.
  2. In fact, thre are no config settings at all. You simply pass the name of the fragment you want to extract when you call the function.
  3. Data is returned as a string instead of appended to the DOM so you can then manipulate it or place it wherever you like.
  4. Uh... it's a jQuery plug-in.

If you'd like a stand-alone solution, I highly recommend you check out JSHTML. It's a great, elegant little piece of code. However, if you're already using jQuery, this is a fast, very lightweight solution that, to my mind, offers a bit more flexibility.

Example:

<div id="fragments">
  <!-- OUTPUT1 {{
    <p>This is the text for output box 1.</p>
  }} -->
      
  <!-- OUTPUT2 {{
    <p>This is the text for output box 2.</p>
  }} -->
  
  <!-- ALERT1 {{
    This is an alert box message.
  }} -->
  
</div>
    
<div id="output_box_1">
</div>
      
<div id="output_box_2">
</div>

<script type="text/javascript">
  function fill_boxes() {
    $('#output_box_1').html($('#fragments').jqfragment('OUTPUT1'));
    $('#output_box_2').html($('#fragments').jqfragment('OUTPUT2'));
    alert($('#fragments').jqfragment('ALERT1'));
  }
</script>

Run the function.

Download:

git clone git://github.com/kellishaver/jqfragment.git

Grab the zip file or the tarball.