Happy new year to everybody ! I would like to get your help because I'm thinking how I can rewrite a little part from my code.
I have a django variable
sets in my context and I pick up this variable in my HTML template
(especially in my JavaScript
part in my HTML template).
It works, but it's not a good idea because I would like to set all JS in one JS file and don't have piece of JavaScript in each HTML template.
In Django I have :
submethods = SubMethod.objects.all()
submethods_item = []
for item in submethods:
submethods_item.append({'id': item.id, 'text': item.name})
context['submethods_item'] = submethods_item
In my HTML template, I have this piece of JavaScript :
function get_sub_method_options(keep_cur) {
var sel_option = $('select#id_method-group').find("option:selected");
var sel_val = sel_option.val();
if (!sel_val) {
$("select#id_method-sub_method").empty();
let all_sub_methods = {{ submethods_item|safe }};
for (var i = 0; i < all_sub_methods.length; i++) {
$("select#id_method-sub_method").append('<option value="' + all_sub_methods[i].id + '">' + all_sub_methods[i].text + '</option>'); //here add list of all submethods
}
return;
};
...
}
As you can see, I get the Django variable here :
let all_sub_methods = {{ submethods_item|safe }};
How I can make the same things, but with a method which let to write JS in my JavaScript file containing Django variable ?
If I write in my HTML template :
<script>
let all_sub_methods = {{ submethods_item|safe }};
</script>
And I write my JS part inside an external file .js, it should work right ?
Thank you !