2011-07-15 27 views
1

我想要實現的是爲所有需要在單獨的js文件中(而不是在頁面中呈現)內部生成的HTML模板存儲HTML模板。JavaScript文件中的HTML模板...我做錯了什麼?

buildHtml函數如何使其當前設置正常工作。當我堅持是什麼,如果..我以前做的模板對象內的另一個變量說「輸入3」和它的標記是一樣的東西<div>(exact markup from commonInput)</div>

我試圖使用它作爲input 3 : '<div>' + this.commonInput + '</div>'但事實證明,你不能指代對象的屬性內部使用this(explained here)

我可以用完整的html創建'input3',但對於大的html塊,這種方法不是很有用。

尋找

  1. 解決這一特定問題
  2. 原因,如果這種做法是一個壞主意
  3. 更好的替代品

    $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(); 
    
    }); 
    
+1

有你使用['_.template'(http://documentcloud.github.com/underscore/#template) – Raynos

回答

1

就在我頭上。

您可以將模板編寫爲構建字符串的函數。

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

則:

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

另外,我喜歡建立HTML時建立自己的DOM對象。並避免使用硬編碼的字符串。

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

+0

謝謝你......幫助表示讚賞! – Adi

+0

您對這種方法在即時創建內容方面有什麼想法......您推薦任何其他方法/解決方案。我在這裏有一個關於這個問題http://stackoverflow.com/questions/6685582/javascript-best-approach-for-managing-adding-content-on-fly-and-page-load – Adi

1

我不知道是什麼你確切的問題是,但只要更好的替代品, 我會建議使用jQuery模板。

這裏是所有不同的模板引擎,其性能基準測試頁面:http://jsperf.com/dom-vs-innerhtml-based-templating

你可以看一下修訂發現引擎的不同組合,以及在不同的瀏覽器中運行他們看到的速度差異。

更新:原來的jquery模板項目不再有效。這是舊項目的新家:https://github.com/BorisMoore/jquery-tmpl

我不會再推薦jquery-templates,因爲現在有更好的選擇。我上次檢查時,dustJs by linkedIn fork似乎是最有希望的。

+0

這種聯繫有腐爛,不幸的是考慮。也許這是你的意思? http://plugins.jquery.com/loadTemplate/ –

+1

取出鏈接並替換爲正確的鏈接。你有一個看起來相似,但不是原來的。 – Mrchief