在视图中:
posts = Posts.objects.filter(...)
template = loader.get_template('...')
context = Context({
'comments': comments,
})
return HttpResponseForbidden(template.render(RequestContext(request, context)))
在模板中:
<script type="text/javascript">
head.js('...');
head.ready(function() {
$(document).ready(function() {
postModel = new postModel({
posts: '{{ posts }}'
});
ko.applyBindings(commentModel, $('#posts')[0]);
});
});
</script>
<ul data-bind="foreach: comments">
....
</ul>
在 post.js 中
self.comments = ko.observableArray(ko.utils.parseJson(config.comments)); //error: Uncaught SyntaxError: Unexpected token &
self.comments = ko.observableArray(config.comments); //error: Uncaught TypeError: Cannot use 'in' operator to search for 'length' in
如何转换数据类型?
{{ posts}}
[<Post: un posts!>, <Post: deux posts!>] to [{id:1, content:'un posts' etc},{...}]