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.

Why would I need this?

For those wondering why you would want something like this, when I first saw the original JSHTML code, it took me a bit to wrap my head around where this would be useful, too. Then I started working on a project that was dynamically generating specific pieces of content contingent upon HTML markup returned from an AJAX call. The response data was different every time and so the code that needed to be dynamically appended to the DOM (in this case, whenever users performed certain actions) was different each time. It was much easier and more efficient to just place that data in the response rather than having to write it into the JavaScript functions. Then I could extract it, in whatever format it took, manipulate it however I wanted to, and render as many new iterations of it as I wanted.

Download:

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

Grab the zip file or the tarball.