Joe*_*ito 3 javascript template-engine mustache
我使用 mustache.js 作为我的客户端模板解决方案,但我遇到了一个问题,我不知道为什么会发生这种情况:
首先,这是我的模板:
<ul>
{{#steps}}
<li>
<a href="{{url}}">
<div class="step_visual {{step_status}}">
<span class="step_description">{{description}}</span>
</div>
</a>
</li>
{{/steps}}
</ul>
Run Code Online (Sandbox Code Playgroud)
这是我试图传入的 json 对象:
var view = {
"steps": [
{
"url": "complete_profile",
"step_status": "done",
"description": "Complete Proflie"
},
{
"url": "complete_form1",
"step_status": "active",
"description": "Submission of Form 1"
}
]
}
Run Code Online (Sandbox Code Playgroud)
我尝试运行此脚本以在我的应用程序中呈现它
var content = Mustache.render(template, view);
$(target).html(content).hide().fadeIn();
Run Code Online (Sandbox Code Playgroud)
where template= 上面的模板 |
view= 视图对象和target是我希望更改内容的 html 元素
让我感到困惑的是,当我的模板看起来像
{{#steps}}
{{url}}
{{description}}
{{step_status}}
{{/steps}}
Run Code Online (Sandbox Code Playgroud)
或者如果我的模板没有任何内容可以循环。
可能是什么错误?你认为这是一个小胡子的错误吗?
编辑 正如我所见,代码有效,
我调用函数的方式可能有问题吗?
tmplReplaceContent : function(json, tmpl, target) {
var regex = new RegExp("\{{[a-zA-Z\.\_]*\}}"),
view = '';
function setOutput(template) {
var content = Mustache.render(template, view);
$(target).html(content).hide().fadeIn();
}
function doJSON(json) {
view = json;
if(!regex.test(tmpl)){
/* get mustache tmpl from the path */
$.get(msi.vars.tmpl_url + tmpl + '.mustache', setOutput);
} else {
setOutput(tmpl);
}
}
/* json -> check if object */
if (typeof json === 'object') {
doJSON(json);
} else {
/* getJSON from the path */
$.getJSON(msi.vars.base_url + json, doJSON);
}
}
Run Code Online (Sandbox Code Playgroud)
我从未有过这种解脱的感觉,因为我已经自己解决了我的问题,首先感谢Tomalak一直关注我的评论并帮助我解决问题。
如果我继续处理 console.logging 的话,我本可以更早地解决这个问题,但我停了下来。
我注意到的一件事是该$.get函数给了我#<Document>,它几乎是一个对象,我本可以早些时候推断出响应是一个对象,从我的问题的标题中可以看出它显然正在返回一个对象。
那么为什么不添加dataType属性呢?
function doJSON(data){
dataSource = data;
if (!regex.test(tpl)) {
$.get(msi.vars.tmpl_url + tpl + '.mustache', render, 'text'); // see here
} else {
render(tpl);
}
}
Run Code Online (Sandbox Code Playgroud)
这最终解决了问题。
| 归档时间: |
|
| 查看次数: |
2057 次 |
| 最近记录: |