3

我使用 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>

这是我试图传入的 json 对象:

var view = {
    "steps": [
        {
            "url": "complete_profile",
            "step_status": "done",
            "description": "Complete Proflie"
        },
        {
            "url": "complete_form1",
            "step_status": "active",
            "description": "Submission of Form 1"
        }
    ]
}

我尝试运行此脚本以在我的应用程序中呈现它

var content = Mustache.render(template, view);
$(target).html(content).hide().fadeIn();

其中template= 上面的模板 | view= 视图对象,并且target是我希望更改内容的 html 元素

让我感到困惑的是,当我的模板看起来像

{{#steps}}
    {{url}}
    {{description}}
    {{step_status}}
{{/steps}}

或者如果我的模板没有任何可循环的内容。

可能是什么错误?你认为这是胡须虫吗?

编辑 正如我所见,代码有效,

我调用函数的方式可能有问题吗?

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);
    }
}
4

1 回答 1

5

我从来没有感到这种解脱的感觉,因为我已经自己解决了我的问题,首先感谢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);
    }
}

这最终解决了问题。

于 2012-12-23T10:58:59.860 回答