如何在JavaScript文件中使用Django变量? [英] How to use Django variable in JavaScript file?
问题描述
我知道我们可以在带有{{variable}}的模板(html文件)中使用Django变量,但是如何在模板中包含的Javascript文件中使用Django变量?
I know that we can use Django variable in templates(html files) with {{variable}}, but how can I use a variable Django in a Javascript file that included in the template?
例如,这是我的template.html:
For example here is my template.html:
<html>
<head>
<script src="/static/youtube.js"></script>
...
如何在 youtube.js 中使用变量{{user.get_username}}?不在template.html中,原因是我没有在此处编写脚本...并且当我在Javascript文件youtube.js中使用{{user.get_username}}时,它导致了错误无效令牌{",但在模板中有效很好.
how can I use variable {{user.get_username}} in youtube.js? not in template.html cause I did't wrote my script here...and when I use {{user.get_username}} in Javascript file youtube.js it caused an error "invalid token { ", but in the template it works fine.
非常感谢!
推荐答案
您需要在脚本标记之前打印它
You need to print it before your script tag
<html>
<head>
<script>
var username = {{user.get_username}};
</script>
<script src="/static/youtube.js"></script>
...
然后,您可以在 youtube.js
中使用 username
变量,因为该变量被声明为javascript全局变量.
Then you can use the username
variable inside your youtube.js
as it is declared as a javascript global variable.
这篇关于如何在JavaScript文件中使用Django变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!