【发布时间】:2011-07-15 01:13:33
【问题描述】:
我想要实现的是将 HTML 模板存储为需要在单独的 js 文件中动态生成的所有内容(而不是在页面中呈现它)。
buildHtml 函数当前设置如何正常工作。我卡住的地方是如果......我在模板对象中有另一个变量说'input3',它的标记类似于<div>(exact markup from commonInput)</div>
我尝试将其用作input 3 : '<div>' + this.commonInput + '</div>',但事实证明您不能使用this(explained here) 从内部引用对象属性。
我可以使用完整的 html 创建“input3”,但对于大 html 块,这种方法不是很有用。
寻找
- 此特定问题的解决方案
- 如果这种方法是一个坏主意的原因
-
更好的选择
$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(); });
【问题讨论】:
-
你考虑过使用
_.template
标签: javascript jquery jquery-templates