[英]Get Django variable in HTML template with Javascript part
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). 我的上下文中有一个
django variable
集,我在HTML template
(尤其是在HTML template
JavaScript
部分中)拾取了此变量。
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. 它可以工作,但这不是一个好主意,因为我想将所有JS设置在一个JS文件中,并且每个HTML模板中都没有JavaScript。
In Django I have : 在Django中,我有:
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 : 在我的HTML模板中,我有这段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 : 如您所见,我在这里获取Django变量:
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 ? 我如何做同样的事情,但是要用一种方法让我在包含Django变量的JavaScript文件中写JS呢?
If I write in my HTML template : 如果我在HTML模板中编写:
<script>
let all_sub_methods = {{ submethods_item|safe }};
</script>
And I write my JS part inside an external file .js, it should work right ? 我将我的JS部分写在一个外部文件.js中,它应该工作正常吗?
Thank you ! 谢谢 !
Your approach might work, but only by accident. 您的方法可能有效,但只是偶然。
Your context variable submethods_item
is a Python list containing dictionaries. 您的上下文变量
submethods_item
是一个包含字典的Python列表。 If you use that variable in a template with the safe
filter, it gets rendered as a string that is valid JavaScript, but there are many ways this can go wrong. 如果在带有
safe
过滤器的模板中使用该变量,则该变量将被呈现为有效JavaScript的字符串,但是有很多方法可能会出错。
The recommended approach is to serialize your variable to JSON, apply the escapejs
in the template and then parse it in JavaScript. 推荐的方法是将变量序列化为JSON,在模板中应用
escapejs
,然后在JavaScript中对其进行解析。
# view
import json
...
context['submethods_item'] = json.dumps(submethods_item)
# template
<script>
let all_sub_methods = JSON.parse("{{submethods_item|escapejs}}");
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.