简体   繁体   中英

how to use context in django

I'm a Django newbie and I have a problem. I'm trying to make my Webapplication a little bit more dynamic. So I want to create the data in the view and set it with Context() in the html document. Here is what I'm trying:

This is the View:

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)

and here is the part of my html document where it should be used:

var dataset = [ {{data}} ];

But it doesn't work. Can someone tell me why and help me how I can make something like this?

Thanks

Simply put, a Context is simply a dictionary that you send to the template. The keys are then available as variables in the template.

Here's an example:

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)

In your template:

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

Use escapejs so that your value is escaped properly for javascript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM