1

I'm trying to pass js variables in a django {% url %}, but with no success. I built a D3 bar chart, and i would like to link each bar to a different page, rendered by django. The pages are working well, and when i push the static data (all bars to the same page) it works well. How should i add js variables?

Thanks!

Shai Efrati
  • 516
  • 1
  • 7
  • 27

2 Answers2

1

You can't: the results of the {% url %} tag are compiled on the server side but the javascript is run on the client side.

You could use an AJAX endpoint to provide the function of the {% url %} tag. Create a view which runs reverse() and returns the result in a JSON response. You could then pass your parameters to it and do something with the result using Javascript. A VERY simplistic example:

urls.py

url(r'^posts/(?P<pk>\d+)$', 'app.views.post', name='post_view'),
url(r'^url$', 'app.views.url_endpoint_view', name='url_endpoint')

views.py

import json
from django.http import HttpResponse

def url_endpoint_view(request):
    name = request.GET.pop('name')
    data = {'url': reverse(name, kwargs=request.GET)}
    return HttpResponse(json.dumps(data), content_type='application/json')

Template:

<a href="#" id="post_link">Dynamic link to a post</a>

JavaScript:

$.get('/url?name=post_view&pk=5', function(data) {
    $('#dynamic_link').attr('href', data.url)
});
ACGray
  • 666
  • 3
  • 10
0

I had the same problem, and I found replace could work on this. Here is my example code:

const html = matches.map(match => 
`<a href="{% url 'case' 9999 %}"class="btn btn-primary btn-block">More Info</a>`.replace(/9999/,match.pk)).join('');

I summarized the code to prevent flood but you could guess what this part does. It first puts /case/9999 for every match, but then it replaces 9999 with the id in primary key, so it's converted to /case/1, /case/3, etc...

If you have the possibility to have 9999 as id, you could change it to anything you want of course.

Plato
  • 89
  • 1
  • 11