graphElem
graphElem

Reputation: 123

Django3: dynamically generating js which I can use in HTML page

As we know in Django framework we can generate the HTML page based on some predefined template files. Inside those templates we can use and some specific django keywords/operators/functions. Like:

{% block stylesheets %}
    <link href="{% static 'js/jquery/jquery-ui.css' %}" rel="stylesheet">
    <link href="{% static 'vendor/chosen/chosen.css' %}" rel="stylesheet">
{% endblock stylesheets %}

But most important things which I want to touch in this question are related to tag 'translate'

"{% trans 'List of all available masters' %}"

So I can be sure that the final content of my page will use some predefined language. And the places where I am using such tags are different: "simple" html content with / and etc tags AND inline javascripts blocks. Like:

<script type="text/javascript">
$('#datepicker_value').on('change', function(){
....
                var dialog = BootstrapModalWrapperFactory.createModal({
                    title: '{% trans 'Extended information about the event' %}',
                    message: '<pre>'+JSON.stringify(info.event.extendedProps.description, null, 4)+'</pre>',
                    buttons: [
                        {
                            label: '{% trans 'Close' %}',
                            cssClass: "btn btn-secondary",
                            action: function (button, buttonData, originalEvent) {
                                return this.hide();
                            }
                        }
                    ]
                });
....
</script>

So my main question here is such: HOW correctly I can move ALL <script>...</script> blocks from html template into the external JS file? To keep all the functionality of the django framework working! And my 1 variant was - I should use the same technique which I use for generating HTMLs with Django framework abilities. But maybe in a little shorten variant: Right inside the views.py file - CAN I somehow correctly generate on the fly full content of GLOBAL.js file which will contains ALL ... blocks from html template - where they all were previously stored. And in a such manner - that standard django template engine can convert all {% ..... %} placeholders in a correct real content BEFORE the full content of GLOBAL.js will be generated and given out. And especially the content of translatable placeholders!!! Well, then in the HTML page template I can insert a call to a special command that can display the contents of this script at the moment the page is rendered by the browser on the client side. Something like:

<script type="text/javascript" src="{% url 'GLOBAL.js' %}"></script>

Am i right? If yes - how I can do that step-by-step? Or maybe there is something new and more logical way? Django version is the latest one!!! 3.*

P.S. Also I've faced with a problem of transferring script block with content like document.addEventListener('DOMContentLoaded', function(){...}); Looks like such event handlers can't be moved out to the separate JS file from HTML page((

Upvotes: 1

Views: 142

Answers (1)

Jaap Joris Vens
Jaap Joris Vens

Reputation: 3550

There is no reason you couldn't use Django template tags inside Javascript files (or any other filetype for that matter). As an example, here's is a view that returns rendered Javascript:

from django.shortcuts import render

def render_javascript(request):
    return render(request, 'myapp/global.js', {})

If you hook this view into your urlpatterns like this:

urlpatterns = [
    path("js/global.js", render_javascript, name="globaljs"),
]

You can then use the {% url %} template tag to refer to it from your HTML templates like this:

<script type="text/javascript" src="{% url 'globaljs' %}"></script>

Now when your browser requests js/global.js, the Django view will take the template myapp/global.js, process it with the templating system, and return the rendered template.

Upvotes: 1

Related Questions