Django Template: How to connect chat script passing in Django Tag with JavaScript?

I’m working on a Django project where I need to conditionally render and execute a chat script based on user cookie consent. Here’s what I’ve got so far:

In my Django template, I have the following snippet:

{% if page.page_type.chat_script %}
  {{ page.page_type.chat_script|safe }}
{% endif %}

This snippet is responsible for rendering a chat script (something like chat script code) which is set via the Django admin panel.

However, I only want this script to execute if the user has accepted all cookies. I already have a separate JavaScript file (cookies_configuration.js) that handles cookie consent and injects various scripts into the head or body once consent is given (it works pretty fine when I use it with normal different scripts placed in other files).

Here’s a simplified example of how that injection looks (a little snippet from my code):

'injections': [
    {
        'location': 'head',
        'code': 'initGoogleAnalytics()'
    },
]

Now, I want to do something similar for the chat script—essentially wrap the Django template snippet in a function like initChatScript() and then call this function only after cookie consent is granted.


However, I’m not sure how to dynamically include and execute this Django template code within the JavaScript function.

I’ve already tried to do something like this:

<script async type="text/javascript">
  function initChatScript() {
    {% if page.page_type.chat_script %}
      {{ page.page_type.chat_script|safe }}
    {% endif %}
  }
</script>

But obviously it didn’t work at all.

What would be the best approach to achieve this? **Is there a way to render the template code conditionally or inject it into the JavaScript function? **Or should I take a different approach altogether (maybe it will be necessary to change the business logic and replace django tags with normal code, probably pure scripts)?

Any help or guidance would be greatly appreciated!