2013-10-31 2 views
0

간단한 대답은 알고 있지만 발견하지 못했습니다. 내 views.py에는 페이지가로드 될 때 실행되는 javascript onload 함수를 추가하는 것을 목표로하는 함수가 있습니다. 페이지가 스크립트와 함께로드되지만 스크립트는 실행되지 않습니다. 아래를 참조하십시오 : 당신은 그와 같은 TemplateResponse를 조작해서는 안django가있는 템플릿 페이지를 제공 할 때 실행할 스크립트를 삽입하십시오.

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 
+0

:

from django.template.response import TemplateResponse context = { 'variable': value, } t = TemplateResponse(request, 'viewer/index.html', context) 

그리고 당신의 템플릿을 태그 외부에 스크립트를 추가하고 있습니다. 또는 으로 가져와야합니다. –

답변

2

이유는 단순히 템플릿의 스크립트를 추가하지? 전용 자바 스크립트 파일에서 더 나은가? 장고보기는 스크립트를 생성하는 데 더 좋은 방법이 아니므로 코드 오류가 발생하기 쉽고 읽고 디버그하기가 더 어려워집니다.

당신이 당신의 js에 파이썬에서 변수를 전달해야하는 경우, 당신은 같은 것을 사용할 수 있습니다 : 당신을 추측하고있어

<html> 
<head></head> 
<body> 
… 
var config = { 
    'variable': {{ variable }} 
} 
<script type="text/javascript" src="path/to/script.js"></script> 
</body> 

1

. 대신 콘텐츠를 올바르게 전달하십시오. 템플릿에서

다음
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> 
관련 문제