V
V
Vladimir Kuts2016-07-23 14:43:37
Django
Vladimir Kuts, 2016-07-23 14:43:37

Best practices for working with javascript?

Let's say I have a repeating block of code that I place in several places on the site. It has a Javascript handler attached to it. There is such a problem - how to actually connect it correctly?
Let's say I include a block with {% include 'some_block.html' %}. Every time remember that it is necessary to separately include the appropriate code with Javascript in the template? Not very flexible...
I solve part of the problem with django-embedded-media. But maybe there is another way?
Another problem is that in the script file I call some url with Ajax. In templates, it is convenient to write a link through {% url 'some_url' param=some_value %}, but what about script files? Hardcode? - Sloppy somehow ... I want a better solution.
How is it generally accepted to look for a way out in these situations?
How is it organized in the "best houses in Paris"?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2016-07-23
@sergey-gornostaev

The first problem is solved by using django-sekizai . In some_block.html include code

{% addtoblock "js" %}
<script type="text/javascript" src="{% static 'js/some_script.js' %}"></script>
</script>
{% endaddtoblock %}

and in the base template
After that, you can be sure that the script will be included in the resulting html document exactly once and in the right place.
To solve the second problem, there are a lot of options. One of them is to include in the template from which the request will occur, the code of the form
<script type="text/javascript">
    window.urls = {
        some_url: {% url 'some_url' param=some_value %}
    }
</script>

And in the script that makes this ajax request, get the url using the urls['some_url'] construct.
Or you can use something like django-js-utils .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question