Search code examples
jqueryjquery-templates

Is it possible to instantiate and cache a jQuery Template as a javascript object?


Thanks for looking!

Background

I realize that jQuery templates has been set aside for some other shiny objects, but I am obligated to using the framework on my current project anyway.

I am writing a dynamic form builder that accepts JSON and then renders the proper form fields, and am binding to a template for one-off controls. For example, a JSON object representing a basic text field would correspond to a template like this:

   <!-- BEGIN TEXTBOX TEMPLATE -->
    <script type="text/html" id="Template_TextBox">
        <div class="formField">
            <label>
                ${LabelText}
                <span class="small">${HelpText}</span>
            </label>
            <input type="text" id="${FieldId}" placeholder="${Placeholder}" />
            <div class="clear10"></div>
        </div>
    </script>
    <!-- END TEXTBOX TEMPLATE -->

The FormBuilder class lives in it's own JavaScript file and will be used throughout the project.

Question

Since this class will be used to render form fields throughout the project, and since those fields will always look the same (i.e. text input, select list, etc), I would like to just standardize the jQuery templates and keep them all in one place rather than have to paste those templates onto every page that has a form. I would prefer to initialize these templates somehow in my FormBuilder.js file with the rest of the form building logic or at the very least have a HTML page somewhere that contains all of the templates and can be referenced by the .js file for use across the site.

Is this possible? If so, how?


Solution

  • This was easier than I thought:

    Step 1: Place your template into a variable as a string of html:

    var myTemplate = "<h1>${someItem}</h1>";
    

    Step 2: Cache the template

    $.template("myTemplate", myTemplate);
    

    Step 3: Use it!

    $.tmpl("myTemplate", myJsonData).appendTo("#SomeHtmlElement");