Isaac Reinaldo
Isaac Reinaldo

Reputation: 49

Django - How to load javascript variable from another file to template

How can I load some variable from another js document inside a template, and then modify this variable inside a script tag in my template?

For example:

js file

let myObject = {color: red}

Django template

{% extends 'app/general/base.html' %}
{% load crispy_forms_tags %}
{% load widget_tweaks %}
{% load static %}

{% block content %}
    <h1 id="color"></h1>

    <script>
        document.getElementById('color').innerHTML = myObject.color //I need some way of loading myObject here, and be able to retrieve and edit data from it
    </script>
{% endblock %}

Upvotes: 1

Views: 1054

Answers (1)

Irfan wani
Irfan wani

Reputation: 5104

That is simple.

<script src="path_to_your_file.js"></script>
<script>        
    console.log(myObject);
</script>

Where path_to_your_file.js is the path to the file where the myObject is present

Upvotes: 1

Related Questions