Django模板 - 将Python列表转换为JavaScript对象

时间:2021-05-12 20:18:22

I am working on a Django / Python website. I have a page where I want to display a table of search results. The list of results is passed in to the template as normal.

我正在研究Django / Python网站。我有一个页面,我想显示搜索结果表。结果列表正常传递给模板。

I also want to make this list of objects accessible to the JavaScript code.

我还想让JavaScript代码可以访问这个对象列表。

My first solution was just create another view that returned JSON format. But each page load required calling the query twice. So then I tried only downloading the data using the JSON view and printing the table using JavaScript.

我的第一个解决方案是创建另一个返回JSON格式的视图。但每次加载页面都需要调用两次查询。因此,我尝试仅使用JSON视图下载数据并使用JavaScript打印表。

But this is also not desirable as now the presentation layer is mixed into the JavaScript code.

但这也是不可取的,因为现在表示层被混合到JavaScript代码中。

Is there a way to create a JavaScript object from the Python list as the page is rendered?

有没有办法在呈现页面时从Python列表创建JavaScript对象?

3 个解决方案

#1


20  

How about a filter that dumps a Python value to JSON? Here's a sample implementation:

将Python值转储到JSON的过滤器怎么样?这是一个示例实现:

http://djangosnippets.org/snippets/201/

http://djangosnippets.org/snippets/201/

Since a JSON value also happens to be a valid right-hand side for a Javascript assignment, you can simply put something like...

由于JSON值恰好也是Javascript赋值的有效右侧,因此您可以简单地添加类似...

var results = {{results|jsonify}};

inside your script.

在你的脚本里面。

#2


18  

Solution

I created a custom template filter, see custom template tags and filters.

我创建了自定义模板过滤器,请参阅自定义模板标记和过滤器。

from django.core.serializers import serialize
from django.db.models.query import QuerySet
from django.utils import simplejson
from django.utils.safestring import mark_safe
from django.template import Library

register = Library()

def jsonify(object):
    if isinstance(object, QuerySet):
        return mark_safe(serialize('json', object))
    return mark_safe(simplejson.dumps(object))

register.filter('jsonify', jsonify)
jsonify.is_safe = True   

The calls to mark_safe are important. Otherwise Django will escape it.

对mark_safe的调用很重要。否则Django会逃脱它。

In the template:

在模板中:

//Without template filter (you'll need to serialise in the view)
var data = jQuery.parseJSON('{{ json_data|safe }}');
alert(data.length);

//Using the template filter    
var data2 = jQuery.parseJSON('{{ record_list|jsonify }}');
alert(data2.length);

Note the single quotes around the template tag.

请注意模板标记周围的单引号。

Although my next question would be - is it REALLY safe?

虽然我的下一个问题是 - 它真的很安全吗?

Update

An updated version working in django 1.8 of the above template tag that also handles being passed a flat values list, ie. values_list('myfield', flat=True):

在上述模板标记的django 1.8中工作的更新版本,它还处理传递平面值列表,即。 values_list('myfield',flat = True):

from django.core.serializers import serialize
from django.db.models.query import QuerySet, ValuesListQuerySet
from django.template import Library

import json

register = Library()

@register.filter( is_safe=True )
def jsonify(object):

    if isinstance(object, ValuesListQuerySet):
        return json.dumps(list(object))
    if isinstance(object, QuerySet):
        return serialize('json', object)
    return json.dumps(object)

#3


0  

Look this answer too.

看看这个答案。

But it isn't highload way. You must:

但它不是高负荷的方式。你必须:

a) Create JSON files, place to disk or S3. In case is JSON static

a)创建JSON文件,放置到磁盘或S3。如果是JSON静态

b) If JSON is dynamic. Generate JSON on separately url (like API) in your app.

b)如果JSON是动态的。在应用中的单独url(如API)上生成JSON。

And, load by JS directly in any case. For example:

而且,无论如何都直接由JS加载。例如:

$.ajax('/get_json_file.json')

$阿贾克斯( '/ get_json_file.json')

P.S.: Sorry for my English.

P.S。:抱歉我的英文。

#1


20  

How about a filter that dumps a Python value to JSON? Here's a sample implementation:

将Python值转储到JSON的过滤器怎么样?这是一个示例实现:

http://djangosnippets.org/snippets/201/

http://djangosnippets.org/snippets/201/

Since a JSON value also happens to be a valid right-hand side for a Javascript assignment, you can simply put something like...

由于JSON值恰好也是Javascript赋值的有效右侧,因此您可以简单地添加类似...

var results = {{results|jsonify}};

inside your script.

在你的脚本里面。

#2


18  

Solution

I created a custom template filter, see custom template tags and filters.

我创建了自定义模板过滤器,请参阅自定义模板标记和过滤器。

from django.core.serializers import serialize
from django.db.models.query import QuerySet
from django.utils import simplejson
from django.utils.safestring import mark_safe
from django.template import Library

register = Library()

def jsonify(object):
    if isinstance(object, QuerySet):
        return mark_safe(serialize('json', object))
    return mark_safe(simplejson.dumps(object))

register.filter('jsonify', jsonify)
jsonify.is_safe = True   

The calls to mark_safe are important. Otherwise Django will escape it.

对mark_safe的调用很重要。否则Django会逃脱它。

In the template:

在模板中:

//Without template filter (you'll need to serialise in the view)
var data = jQuery.parseJSON('{{ json_data|safe }}');
alert(data.length);

//Using the template filter    
var data2 = jQuery.parseJSON('{{ record_list|jsonify }}');
alert(data2.length);

Note the single quotes around the template tag.

请注意模板标记周围的单引号。

Although my next question would be - is it REALLY safe?

虽然我的下一个问题是 - 它真的很安全吗?

Update

An updated version working in django 1.8 of the above template tag that also handles being passed a flat values list, ie. values_list('myfield', flat=True):

在上述模板标记的django 1.8中工作的更新版本,它还处理传递平面值列表,即。 values_list('myfield',flat = True):

from django.core.serializers import serialize
from django.db.models.query import QuerySet, ValuesListQuerySet
from django.template import Library

import json

register = Library()

@register.filter( is_safe=True )
def jsonify(object):

    if isinstance(object, ValuesListQuerySet):
        return json.dumps(list(object))
    if isinstance(object, QuerySet):
        return serialize('json', object)
    return json.dumps(object)

#3


0  

Look this answer too.

看看这个答案。

But it isn't highload way. You must:

但它不是高负荷的方式。你必须:

a) Create JSON files, place to disk or S3. In case is JSON static

a)创建JSON文件,放置到磁盘或S3。如果是JSON静态

b) If JSON is dynamic. Generate JSON on separately url (like API) in your app.

b)如果JSON是动态的。在应用中的单独url(如API)上生成JSON。

And, load by JS directly in any case. For example:

而且,无论如何都直接由JS加载。例如:

$.ajax('/get_json_file.json')

$阿贾克斯( '/ get_json_file.json')

P.S.: Sorry for my English.

P.S。:抱歉我的英文。