如何在django中使用上下文

时间:2015-09-05 12:23:55

标签: python django

我是Django的新手,我有一个问题。我正在尝试使我的Web应用程序更具动态性。所以我想在视图中创建数据,并在html文档中使用Context()进行设置。这是我正在尝试的:

这是视图:

def test(request):

c = Context({"data": "{ label: 'Abulia', count: 10, start: 0, end: 10, radius: 10 }, { label: 'Betelgeuse', count: 20, start: 10, end: 20, radius: 20 }"})
t = get_template('graphtest.html')
html = t.render(c)
return HttpResponse(html)

以下是我的html文档中应该使用的部分:

var dataset = [ {{data}} ];

但它不起作用。 有人可以告诉我为什么,并帮助我如何制作这样的东西?

由于

1 个答案:

答案 0 :(得分:2)

简而言之, Context 只是您发送到模板的字典。然后,这些键可用作模板中的变量。

以下是一个例子:

from django.shortcuts import render

def test(request):
   ctx = {"data": "{ label: 'Abulia', count: 10, start: 0, end: 10, radius: 10 }, { label: 'Betelgeuse', count: 20, start: 10, end: 20, radius: 20 }"}
   return render(request, 'graphtest.html', ctx)

在你的模板中:

var dataset = [ {{ data|escapejs }} ];

使用escapejs,以便为javascript正确转义您的值。

相关问题