I need middleware just like contib.messages, but to insert specific JS code to page from views instead of message. Is there a ready-made solutions or any ideas how to do this?
Asked
Active
Viewed 314 times
1 Answers
0
Files specific to view and tied to processing/data
This is supposing you need your JS files to be specific to your view and need to vary according to your view data.
You don't need middlewares. Pass the url/name of your script to your template from your view using the context and use the variable in the template.
# views.py
class SomeView(TemplateView):
template_name = "app/template.html"
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context["js_url"] = "https://some.url/file.js"
context["js_static"] = "app/local_file.js"
return context
{# templates/app/template.html #}
[...]
{% load static %}
<p>Your content</p>
<script src="{{ js_url }}"></script>
<script src="{% static js_static %}"></script>
Files specific to template
If you only need the JS to be specific to the template and doesn't need to vary according to any processing inside the view, just use the urls/static locations in the template.
Files for a whole site
If you need the same scripts on every page, you should instead create a base template, add your scripts there and make all your templates inherit the base one.

Gabriel
- 734
- 11
- 26