I'm grappling with the best way to structure my javascript and django code.
Previously, I would include my page-specific javascript directly in the template file within a <script>
tag. However, as my javascript code grew, this approach led to a messy situation:
- Mixing django template variables {{var}}
within my JS code made it less readable,
- I encountered errors when attempting to minify the code using tools like ,
- Overall, I felt the need to separate my JS and Django code more effectively.
Currently, my embedded <script>
tag contains JS code like this:
var app = {
func: function() {
// Can I use the {% url %} tag here?
$.post('/url/', {csrfmiddlewaretoken:'{{csrf_token}}', something:'value'} )
},
jsonFromServer: '{{pythonDict|safe}}', // This data structure is essential,
};
There are specific values that need to be passed from Django to JavaScript, such as the csrftoken for ajax requests and sometimes a json dictionary required by the app itself. Occasionally, I may need to pass the server time as well.
I'm contemplating moving the JS code to a separate file as I've heard it's a better organizational practice. However, I'm unsure how to achieve this in a standard Django application without having Django render the .js files. I also prefer not to have Django serve the JS file directly. How can I structure my JS code to minimize the amount of Django-specific code within it?