django将数据传递到javascript的最佳方法 [英] django best way to pass data to javascript

查看:63
本文介绍了django将数据传递到javascript的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在发现数据绑定库之前,我曾经将数据绑定"到DOM.我的问题是,我有一个包含模型记录的表,如何用JS构建该表,即将对象传递给javascript,而不是直接在模板中构建该表?

I used to "tie" my data to the DOM until I've discovered the data binding libraries. My question, say I have a table which contains model records, how can I build that table with JS, i.e pass the objects into javascript rather then straight build the table in template?

到目前为止,搜索是我发现的唯一方法:

so far from searching the only way I've found is things like this:

var data = '{{data}}';  

在此示例中,

{{data}} 可以是json.

{{data}} could be json for this example.

将模板代码放在javascript中对我来说似乎很丑陋和不好,而且我也不喜欢javascript中的全局变量的想法(过时且缩放性不佳).它还不允许我将其放入外部JS文件中.有没有更好(更干净)的方法?

which seems ugly and bad to me, to put template code in javascript, and also I don't like the idea of global variables in javascript (old way and it does not scale well). It also won't allow me to put that in external JS file. Is there's a better (and clean) way?

推荐答案

django模板自动转义所有标签{{}}.

django template autoescape all tags {{ }}.

如果table_data已经在模板标记中为json数据.很简单.

If table_data already json data in template tag. Simple.

<script>
var myTable = {% autoescape off %}{{ table_data }}{% endautoescape %};
</script>

不需要括号和引号,它是javascript中的数组(例如var example = ['test'];)

not need bracket and quote, it's array in javascript (such as var example = ['test'];)

如果数据不是json,请在请求中将其返回(渲染模板).例子

If data not json, return it in request (render template). Example

import json
from django.shortcuts import render

def home(request):
    table_data = MyModel.objects.select_related().values('items1', 'items2')
    return render(
        request, 
        'main.html', 
        {
          'table_data': json.dumps(list(table_data))
        }) 

这篇关于django将数据传递到javascript的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆