EN VI

Javascript - I have a problem with static files in django?

2024-03-12 19:30:04
How to Javascript - I have a problem with static files in django

I cant refrence to contexts in js

HTML

{% load static%}
{%block content%}
    <div id="backSign" , style="display: none;">go to lesions</div>
    <ol id="list"></ol>
{% endblock content%}
{% block extrajs %}
<script src="{% static 'assets/js/idioms.js'%}"></script>
{% endblock extrajs %}

JS

const Data = '{{ data|escapejs }}'
console.log(Data)

output : "{{ data|escapejs }}"

when i put js in script tag it works but when i refrence the place its return this : {{ data|escapejs }}

Solution:

  1. For small amounts of dynamic data or scripts, keep the JavaScript code inside your Django template inside
  2. Store your dynamic data in a data attribute within an HTML element and read this data from your external JavaScript file.

document.addEventListener("DOMContentLoaded", function() {
    const dataElement = document.getElementById('data');
    const Data = dataElement.getAttribute('data-data');
    console.log(Data);
});
{% load static %}
{% block content %}
    <div id="backSign" style="display: none;">go to lesions</div>
    <div id="data" data-data='{{ data|escapejs }}'></div>
    <ol id="list"></ol>
{% endblock content %}
{% block extrajs %}
<script src="{% static 'assets/js/idioms.js' %}"></script>
{% endblock extrajs %}

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login