M
M
Mike2017-04-19 23:26:26
Django
Mike, 2017-04-19 23:26:26

How to use data from model in javascript files?

Why can't I get a variable in a javascript file? For example, I define a variable in the main.js
file in this way and it does not work. I have to first define this variable in the HTML file and then only connect main.js to the end of the file, in this way, and only then in the main.js file can I access this "bar" variable:
var bar = "{{ user.username }}"

<script src="/static/demo/js/main.js"></script>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman Kitaev, 2017-04-19
@deliro

Obviously because JS files are not rendered by the Django template engine.

S
sim3x, 2017-04-20
@sim3x

For one variable

<div
id="user" 
data-username="{{ user.username }}">

<script>
var _user = document.getElementById('user');
var username = _user.dataset.username;

https://developer.mozilla.org/en-US/docs/Learn/HTM...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question