在外部 JavaScript 文件中使用 Django 模板变量
Using django template variables in a external JavaScript file
我想使用链接到模板的 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 }}');
除非你的 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);
我想使用链接到模板的 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 }}');
除非你的 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);