简体   繁体   中英

Django Passing arguments to linked .js script template

I am presenting some graphs using highcharts. Each graph is defined with a block of javascript. I don't particularly want to repeat the same code for each .html template that renders a page with a graph, so I was thinking of writing a .js template with the highcharts code and loading this with a line like:

<script type="text/javascript" src="/some/url/to/myfile.js"></script>

So the basic flow is: Browse to some URL > urls.py calls myHtmlView() > renders an html template > calls an external .js script > urls.py calls myJsView() > renders a js template > A graph appears on a webpage somewhere.

However, I have quite a few arguments to feed to the view which renders this .js template. Currently I am passing these arguments in the url, but it feels clumsy as the urls are getting very long, and the regex to read them is not very readable. Further, I would like to pass in some lists, or even some querysets. Is there some better way I can store the code for the graphs in an external template? Are there other options for passing arguments to it, other than encoding them in the url and reading these in urls.py?

I hope this makes sense, and that it is on topic.

edit: For completeness:

#urls.py
urlpatterns = patterns(
    (r'^/graph/$', views.myhHtmlView),
    (r'^/js/(?P<myVar>\d+/$', views.myJsView),
    )

#views.py
myHtmlView(request):
    context = {'myVar': 42}
    render(request, 'htmlTemplate.html', context)

myJsView(request, myVar):
    context = {'myVar': myVar}
    render(request, 'jsTemplate.js', context, content_type='text/javascript')

#htmlTemplate.html
<script type="text/javascript" src="/js/{{ myVar }}"></script>
#and the rest of the page...

#jsTemplate.js
#some javascript here for rendering the graph, which uses {{ myVar }}...

Answering my own question. It seems the best way to do this is using a custom inclusion_tag : https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#inclusion-tags

So I now have:

#urls.py
urlpatterns = patterns(
    (r'^/graph/$', views.myhHtmlView),
    )

#myApp/views.py
myHtmlView(request):
    context = {'myVar': 42}
    render(request, 'htmlTemplate.html', context)

#myApp/templatetags/myTags.py
from django import template

myJsView(request, myVar):
    jsContext = {'myVar': myVar}
    return jsContext

register = template.Library()
register.inclusion_tag('jsTemplate.js', takes_context=True)(myJsView)

#htmlTemplate.html
#some html here...
<script type="text/javascript">{% myJsTag myVar %}</script>
#and the rest of the page...

#jsTemplate.js
#some javascript here for rendering the graph, which uses {{ myVar }}...

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