Using Django Template Tags in HTML Scripts

Using Django template tags in script

I wondered how to use the Django setting variables inside a <script> tag in an HTML template in one of the projects. In this post, we’ll explore how to effectively use Django template tags in HTML scripts, providing a convenient way to integrate dynamic data and behaviour into your web pages.

Inside the script, I was doing an ajax call to another service in the mesh, and I couldn’t just write the service domain URL and path there like a garbage dump.

After defining the URLs and the path in settings.py

//settings.py
CLIENT_CONF = {
    'base_url': env('BASE_URL'),
    'path': env('PATH'),
}

We need to create a template tag to fetch the required value. Create a template_tags.py file in your app and create a template tag.

from django import template
from django.conf import settings

register = template.Library()


@register.simple_tag
def client_conf(name):
    conf = getattr(settings, "CLIENT_CONF", {})
    return conf.get(name, "")

After that, we need to register this to the Django template view system using TEMPLATES in settings.py.

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [BASE_DIR / 'templates'],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
            "libraries":{
                "template_tags": "my_app.template_tags",
            }
        },
    },
]

Now we’re ready to fetch configs. All you have to do this call the template tag you’ve created properly.

<script type="text/javascript">
    // like this:
    var url = "{% ml_flask_conf 'base_url' %}{% ml_flask_conf 'predict_single' %}";
    var data = {};
    $("#my-button").click(function () {
        //var data = Object.fromEntries($("#predict-form").serializeArray());
        var formData = {
            ...
        };
        $.ajax({
            url: "{% ml_flask_conf 'base_url' %}{% ml_flask_conf 'predict_single' %}",
            method: "POST",
            contentType: "application/json",
            dataType: "json",
            ...
        });
    });
</script>

That’s it. I know it’s a short post but you can learn more about template tags if you’re using Django template view in your projects heavily.