Javascript 插入要在使用django服务模板页时运行的脚本
我知道有一个简单的答案,但我还没有找到。在my views.py中,我有一个函数,旨在添加一个javascript onload函数,以便在页面加载时运行。页面加载了脚本,但脚本未运行。见下文:Javascript 插入要在使用django服务模板页时运行的脚本,javascript,django,onload,Javascript,Django,Onload,我知道有一个简单的答案,但我还没有找到。在my views.py中,我有一个函数,旨在添加一个javascript onload函数,以便在页面加载时运行。页面加载了脚本,但脚本未运行。见下文: from django.template.response import TemplateResponse t = TemplateResponse(request, 'viewer/index.html', {}) t.render() t.content = t.content + "<scr
from django.template.response import TemplateResponse
t = TemplateResponse(request, 'viewer/index.html', {})
t.render()
t.content = t.content + "<script type='text/javascript'>window.onload=function(){alert('here');}" + "</script>"
return t
来自django.template.response导入TemplateResponse
t=TemplateResponse(请求'viewer/index.html',{})
t、 render()
t、 content=t.content+“window.onload=function(){alert('here');}”+“
返回t
您不应该像那样操纵模板响应。相反,请正确地传递内容
from django.template.response import TemplateResponse
script = "window.onload = function(){ alert('here'); }"
t = TemplateResponse(request, 'viewer/index.html', {
"script": script
})
t.render()
return t
然后在模板中
<html>
<body>
<script>{{ script }}</script>
</body>
</html>
{{script}}
您不应该像那样操纵模板响应。相反,请正确地传递内容
from django.template.response import TemplateResponse
script = "window.onload = function(){ alert('here'); }"
t = TemplateResponse(request, 'viewer/index.html', {
"script": script
})
t.render()
return t
然后在模板中
<html>
<body>
<script>{{ script }}</script>
</body>
</html>
{{script}}
为什么不简单地将脚本添加到模板中?或者更好,在专用javascript文件中?Django视图并不是生成脚本的最佳模板,它会使代码容易出错,并且更难阅读和调试
如果需要将变量从python传递到js,可以使用以下方法:
from django.template.response import TemplateResponse
context = {
'variable': value,
}
t = TemplateResponse(request, 'viewer/index.html', context)
在模板中:
<html>
<head></head>
<body>
…
var config = {
'variable': {{ variable }}
}
<script type="text/javascript" src="path/to/script.js"></script>
</body>
…
变量配置={
'variable':{{variable}
}
为什么不简单地在模板中添加脚本呢?或者更好,在专用javascript文件中?Django视图并不是生成脚本的最佳模板,它会使代码容易出错,并且更难阅读和调试
如果需要将变量从python传递到js,可以使用以下方法:
from django.template.response import TemplateResponse
context = {
'variable': value,
}
t = TemplateResponse(request, 'viewer/index.html', context)
在模板中:
<html>
<head></head>
<body>
…
var config = {
'variable': {{ variable }}
}
<script type="text/javascript" src="path/to/script.js"></script>
</body>
…
变量配置={
'variable':{{variable}
}
我猜您是在标记之外附加脚本。您可能需要将其放入or中。我猜您是在标记之外附加脚本。你可能需要把它放进手术室。