2011-07-15 26 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