【问题标题】:Using django template variables in a external JavaScript file在外部 JavaScript 文件中使用 django 模板变量
【发布时间】:2023-03-21 06:04:01
【问题描述】:
我想在链接到模板的 javascript 文件中使用模板变量。
例如。
<!-- The template -->
<h1>{{ user.username }}</h1>
<script src="{% static 'profile_page/js/index.js' %}"></script>
// The script file (a different file)
console.log('{{ user.username }}');
【问题讨论】:
标签:
django
templates
jinja2
【解决方案1】:
除非您的 index.js 也是由 Jinja 模板生成的,否则在 index.js 中包含 {{ user.username }} 将会很麻烦。
更简单的方法是生成一个<script> 标记,其中包含您的index.js 需要的数据。因为var username = ...; 可以在在后续脚本中访问。
<script>var username = {{ user.username|tojson }};</script>
<script src="{% static 'profile_page/js/index.js' %}"></script>
现在在您的index.js 中,您可以像往常一样简单地使用该变量,即:
console.log(username);