简体   繁体   中英

How to pass javascript variable to Django template

This piece of code is a javascript variable which passes url to a callback function and clicking on certian part of a map renders associated views and subsequently the template "Country_Details.html"

var var_1 = "{% url 'County_Details' pk=1 %}"

In the given example, I have passed an argument, that was "pk=1" it work fine fetched the object associated with the "id" = 1.

def County_Details(request,pk):
    C_Details = CountryDiseases.objects.filter(country__pk=pk)
    return render(request, 'DATAPLO/Country_Details.html', {'C_Details': C_Details })

but I have a list of ids and I want a solutions that can replace the pk values dynamically according to clicks through a variable, say, "my_id".

Though i have tried many things but nothing is working for me. A very close thread as of mine, I found on web is given bellow.

Get javascript variable's value in Django url template tag

I have tried all the solution suggested but nothing is working.

How could I solve this problem.

Thanks

There's a couple things to know about django and templates and js. 1. All django code is server side. It is evaluated on the server BEFORE it gets to the end user. 2. All javascript is client side. It is evaluated AFTER it gets to the user. 3. Django template logic can be considered django code and therefor is also server side (evaluated BEFORE it gets to the end user). 4. You can intermix django template tags and js but only in templates that are rendered, not seperate js files. If you do this, realize that the django template logic is only dynamic on the server. It essentially acts as place holders that hold a single, value that, once on the client will never change. In other words, javascript cannot manipulate django template tag logic. but django template tag logic can manipulate javascript logic ONCE while being rendered by server.

That may not necessarilly be useful in this case but it might help a little with understanding.

So try this:

in mytemplate.html:

var url_option1 = "{% url 'my_url', pk = django_var_1, somevar = django_var_2, ... %}";
var url_option2 = "{% url 'my_url', pk = " + {{ django_var_1 }} + ", somevar = " + {{ django_var_2 }} + " %}";

I'm not sure if that first option will work syntactically. If so, use that and don't do the second one. Otherwise, I know that the second one will always work syntactically but doesn't look as clean. So if syntax works, use the first one.

For the second one, if {{ django_var_? }} returns a string, you will need to put single quotes around the " + {{ django_var_? }} + " like so:

var url_option2 = "{% url 'my_url', pk = '" + {{ django_var_1 }} + "', somevar = '" + {{ django_var_2 }} + "' %}";

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