Search code examples
javascriptjqueryjquery-templates

HTML templates inside JavaScript file... What am I doing wrong?


What I'm trying to achieve is to store HTML templates for everything that needs to be generated on the fly inside a separate js file (instead of rendering it in the page).

The buildHtml function how its currently setup works fine. Where I'm stuck is what if.. I've another variable inside the template object say 'input3' and its markup is something like <div>(exact markup from commonInput)</div>

I tried using it as input 3 : '<div>' + this.commonInput + '</div>' but it turns out you cannot refer object properties from inside using this (explained here).

I could create 'input3' with full html but for big html chunks this approach is not very useful.

Looking for

  1. solution to this specific problem
  2. reasons if this approach is a bad idea
  3. better alternatives

    $j(document).ready(function() {
    
    var namespace = window.namespace || {};
    namespace.feature = namespace.appName || {};
    
    namespace.feature.templates = {
    
    input1  :   '<div>'+
                    '<p class="abc">Hey {username}</p>'+
                '</div>',
    
    input2  :   '<div>'+
                    '<div class="description">{description}</div>'+
                '</div>',
    
    commonInput :   '<div class="common">Common code</div>'
    
    };
    
    namespace.feature.module = function() {
    
    var container  = $j('#container'),
        t = namespace.feature.templates;
    
    var buildHtml = function(type) {
        var tmpHtml = t.input1 + t.commonInput + t.input2;
        container.append(tmpHtml);
    }
    
    var init = function() {
        buildHtml();
    }
    
    return {
        init : init,
    };
    
    }();
    
    namespace.feature.module.init();
    
    });
    

Solution

  • just on the top of my head.

    You could write the templates as functions that build strings.

    input3 : function(param) {
        return '<div>' + param + '</div>'
    }
    

    then:

    var tmpHTML = t.input1 + t.input2 + t.input3(t.commonInput);
    

    Also, i like to build my own DOM objects when building HTML. and avoid the use of hardcoded strings.

    http://mg.to/2006/02/27/easy-dom-creation-for-jquery-and-prototype