【发布时间】:2021-09-22 20:19:18
【问题描述】:
这个线程here 讨论了在模板中使用内联 JavaScript 中的变量。如果我有单独的包含脚本的 .js 文件,则位于 static 文件夹中,例如:
utils.js
const createButton = (buttonCount) => {
containerId = "myContainerId"
container = document.getElementById(containerId)
for (var i = 0; i < buttonCount; i++) {}
newButton = document.createElement("button")
newButton.value = "Test"
newButton.id = "testButton" + i
container.appendChild(newButton)
}
}
createButton(buttonCount)
mytemplate.html
{% extends "base.html" %}
{% load static %}
{% block title %}Testpage{% endblock %}
{% block content-main %}
<link href="{% static "css/mycss.css" %}" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.4.0/css/bulma.css" />
<div id="myContainerId"></div>
<script src="{% static 'js/utils.js' %}"> </script>
{% endblock %}
如果我有一个变量 buttonCount 通过视图函数的上下文传递到此模板,我如何将它传递到 utils.js 文件以由函数 createButton() 调用?
views.py
def button_view(request):
...
buttonCount = 5
return render(request, 'mytemplate.html', {'buttonCount': buttonCount})
【问题讨论】:
标签: javascript django django-templates