A
A
asmrnv7772017-05-03 17:56:34
JavaScript
asmrnv777, 2017-05-03 17:56:34

How to correctly organize the use of JS in Django templates?

There is a template for dzhanga, which uses JS quite actively (a template for 300 lines, 200 of them are JS).
As I understand it, it would be nice to put the JS in a separate file, but some variables in the JS code are initialized by the django template engine, for example:
var currentTopicId = {{ topics.first.pk }};
In addition, there are DOM objects obtained by ID:
var topicTitleElement = $('#topic-title');
If I put the code in a JS file, but leave initialization currentTopicIdin the template, then PyCharm will swear at an unknown variable (there shouldn’t be an error in runtime, but it’s uncomfortable to work). Also, PyCharm won't know the ID of the DOM elements I'm looking for (same #topic-title). In general, it will not be very convenient to work.
Maybe there are some nicer ways to do it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
sim3x, 2017-05-03
@asmrnv777

<body data-attrib="{{ some_var }}">
and $(document).ready(...)enough to solve problems

N
ns5d, 2017-05-03
@ns5d

Alternatively:
html:

<div id="p1" style="display:none">value1</div>
 <div id="p2" style="display:none">value2</div>
 <div id="p3" style="display:none">value3</div>

js:
var p1 = $("#p1").text();
var p2 =  $("#p2").text();
var p3 =  $("#p3").text();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question