我如何将接收到的数组传递给下划线模板

How do i pass a received array into underscore template

我从 PHP 得到一个包含各种数据对象的长数组。

[{"commid":"1","uid":"0","pid":"3","comment":"comm","parid":null,"date":"2016-10-27 15:03:10"},
{"commid":"2","uid":"0","pid":"10","comment":"Ana","parid":null,"date":"2016-10-27 15:03:51"},
{"commid":"3","uid":"0","pid":"5","comment":"asss!","parid":null,"date":"2016-10-27 15:05:50"},
{"commid":"4","uid":"0","pid":"10","comment":"Lawl?","parid":null,"date":"2016-10-27 17:03:59"},
{"commid":"5","uid":"0","pid":"14","comment":"sd","parid":null,"date":"2016-11-06 00:25:04"},
{"commid":"6","uid":"0","pid":"14","comment":"sds","parid":null,"date":"2016-11-06 00:25:50"},
{"commid":"7","uid":"0","pid":"14","comment":"WOW!","parid":null,"date":"2016-11-08 15:06:18"},
{"commid":"8","uid":"0","pid":"13","comment":"Hello!?","parid":null,"date":"2016-11-08 15:14:30"}] 

我的 Backbone 将呈现数据的视图是

var WorkPage = Backbone.View.extend({
    el: $('#indexcontent'),
    render: function() {
        Backbone.history.navigate('work');
        var _this = this;

        this.$el.html(workHTML);
        $.ajax({
            type: "GET",
            url: "includes/server_api.php/work",
            data: '',
            cache: false,
            success: function(html) {
                console.log(html);
                var compiledTemplate = _.template($('#content-box').html(), html);
                _this.$el.html(compiledTemplate);
            },
            error: function(e) {
                console.log(e);
            }
        });
        return false;
    }
});

我的作品将由 Underscore 呈现的 HTML 是

<script type="text/template" id="content-box">
<div class="workhead">
    <h3 class="msg comment"><%= comment%></h3>
    <p class="date"><%= date%></p>
</div>
</script>
<div id="content-box-output"></div>

如何在这里实现下划线循环?

在您的 index.html 文件中,您需要有 _.each() 方法来遍历每个元素

<% _.each(obj, function(elem){ %>
<div class="workhead">
    <h3 class="msg comment"><%= elem.comment %></h3>
    <p class="date"><%= elem.date%></p>
</div>
<% }) %>

我对您的回复进行了修改,只是为了有数据可供使用。在您的视图中,您需要在模板上设置点 template: _.template($("#content-box").html()),并且在 render 方法中仅将数据作为对象发送。

这是工作代码:jsFiddle

这是为数据数组中的每个值加载模板的一种方法。

var WorkPage = Backbone.View.extend({
    el: $('#indexcontent'),
    render: function() {
        Backbone.history.navigate('work');
        var _this = this;

        this.$el.html(workHTML);
        $.ajax({
            type: "GET",
            url: "includes/server_api.php/work",
            data: '',
            cache: false,
            success: function(data) {
                console.log(data);
                var $div = $('<div></div>');
                _.each(data, function(val) {
                    $div.append(_.template($('#content-box').html(), val));
                });
                _this.$el.html($div.html());
            },
            error: function(e) {
                console.log(e);
            }
        });
        return false;
    }
});

您应该利用 Backbone 的功能。为此,您需要了解如何将 REST API 与 Backbone.

一起使用

Backbone's Model 用于管理单个对象并处理与 API 的通信(GETPOSTPATCHPUT 请求)。

Backbone's Collection 作用是处理模型数组,它处理获取它(GET 请求应该 return 一个 JSON 对象数组)并且它还默认情况下将每个对象解析为 Backbone 模型。

不要硬编码 jQuery ajax 调用,而是使用 Backbone 集合。

var WorkCollection = Backbone.Collection.extend({
    url: "includes/server_api.php/work",
});

然后,模块化您的视图。为您收到的数组的每个对象制作一个项目视图。

var WorkItem = Backbone.View.extend({
    // only compile the template once
    template: _.template($('#content-box').html()),
    render: function() {

        // this is how you pass data to the template
        this.$el.html(this.template(this.model.toJSON()));

        return this; // always return this in the render function
    }
});

那么您的列表视图如下所示:

var WorkPage = Backbone.View.extend({
    initialize: function(options) {
        this.itemViews = [];
        this.collection = new WorkCollection();

        this.listenTo(this.collection, 'reset', this.render);

        // this will make a GET request to
        // includes/server_api.php/work
        // expecting a JSON encoded array of objects
        this.collection.fetch({ reset: true });
    },
    render: function() {
        this.$el.empty();
        this.removeItems();
        this.collection.each(this.renderItem, this);
        return this;
    },

    renderItem: function(model) {
        var view = new WorkItem({
            model: model
        });
        this.itemViews.push(view);
        this.$el.append(view.render().el);
    },
    // cleanup to avoid memory leaks
    removeItems: function() {
        _.invoke(this.itemViews, 'remove');
        this.itemViews = [];
    }

});

在 render 函数中设置 url 是不常见的,您应该将职责范围限定在正确的位置。

路由器可能是这样的:

var Router = Backbone.Router.extend({
    routes: {
        'work': 'workPage'
    },

    workPage: function() {
        var page = new WorkPage({
            el: $('#indexcontent'),
        });
    }
});

那么,如果您想查看作品页面:

var myRouter = new Router();

Backbone.history.start();

myRouter.navigate('#work', { trigger: true });

模板和 RequireJS

My index.html page contains this indexcontent div but the content-box which contains the template format which we are compiling is stored in different work.html. So, if i dont load this work.html in my main index.html i am unable to access content-box.

我建议使用 text require.js plugin 并像这样为视图加载每个模板:

工作-item.js文件:

define([
    'underscore', 'backbone',
    'text!templates/work-item.html',
], function(_, Backbone, WorkItemTemplate) {
    var WorkItem = Backbone.View.extend({
        template: _.template(WorkItemTemplate),
        /* ...snip... */
    });
    return WorkItem;
});

工作-page.js文件:

define([
    'underscore', 'backbone',
    'text!templates/work-page.html',
], function(_, Backbone, WorkPageTemplate) {
    var WorkPage = Backbone.View.extend({
        template: _.template(WorkPageTemplate),
    });
    return WorkPage;
});