장고 템플릿 변수와 자바 스크립트
Django 템플릿 렌더러를 사용하여 페이지를 렌더링 할 때 다양한 값을 포함하는 사전 변수를 전달하여을 사용하여 페이지에서 해당 값을 조작 할 수 있습니다 {{ myVar }}
.
Javascript에서 동일한 변수에 액세스하는 방법이 있습니까 (아마 DOM을 사용하면 Django가 변수에 액세스하는 방법을 모르겠습니다)? 전달 된 변수에 포함 된 값을 기반으로 AJAX 조회를 사용하여 세부 정보를 조회 할 수 있기를 원합니다.
이 {{variable}}
HTML로 직접 대체됩니다. 뷰 소스를 수행하십시오. "가변"또는 이와 유사한 것이 아닙니다. 방금 렌더링 된 텍스트입니다.
그렇게 말하면, 이런 종류의 대체물을 JavaScript에 넣을 수 있습니다.
<script type="text/javascript">
var a = "{{someDjangoVariable}}";
</script>
이것은 "동적"자바 스크립트를 제공합니다.
주의 Django 코어에 유사한 태그를 추가하고이 템플릿 태그를 사용자 생성 데이터와 함께 사용하여 발생 가능한 XSS 취약성에 대해 논의 하려면 티켓 # 17419 를 확인하십시오 . amacneil의 의견 은 티켓에서 제기 된 대부분의 문제를 설명합니다.
가장 유연하고 편리한 방법은 JS 코드에서 사용하려는 변수에 대한 템플릿 필터를 정의하는 것입니다. 이 데이터가 제대로 이스케이프와 같은 복잡한 데이터 구조로 사용할 수 있습니다, 당신을 보장 할 수 dict
와 list
. 그래서 많은 찬성에 대한 답변이 있지만이 답변을 작성합니다.
템플릿 필터의 예는 다음과 같습니다.
// myapp/templatetags/js.py
from django.utils.safestring import mark_safe
from django.template import Library
import json
register = Library()
@register.filter(is_safe=True)
def js(obj):
return mark_safe(json.dumps(obj))
이 템플릿 필터는 변수를 JSON 문자열로 변환합니다. 다음과 같이 사용할 수 있습니다.
// myapp/templates/example.html
{% load js %}
<script type="text/javascript">
var someVar = {{ some_var | js }};
</script>
나를 위해 일한 해결책은 템플릿에서 숨겨진 입력 필드를 사용하는 것입니다.
<input type="hidden" id="myVar" name="variable" value="{{ variable }}">
그런 다음 자바 스크립트로 값을 가져옵니다.
var myVar = document.getElementById("myVar").value;
Django 2.1부터이 사용 사례를 위해 새로운 내장 템플릿 태그가 도입되었습니다 json_script
.
https://docs.djangoproject.com/en/2.1/ref/templates/builtins/#json-script .
새로운 태그는 템플릿 값을 안전하게 직렬화하고 XSS로부터 보호합니다.
사전의 경우 먼저 JSON으로 인코딩하는 것이 가장 좋습니다. simplejson.dumps ()를 사용하거나 App Engine의 데이터 모델에서 변환하려면 GQLEncoder 라이브러리에서 encode ()를 사용할 수 있습니다.
내가하는 일이 매우 쉽습니다. 템플릿의 base.html 파일을 수정하고 맨 아래에 배치했습니다.
{% if DJdata %}
<script type="text/javascript">
(function () {window.DJdata = {{DJdata|safe}};})();
</script>
{% endif %}
그런 다음 자바 스크립트 파일에서 변수를 사용하려면 DJdata 사전을 만들고 json으로 컨텍스트에 추가하십시오. context['DJdata'] = json.dumps(DJdata)
그것이 도움이되기를 바랍니다!
S.Lott가 제안한 비슷한 문제와 대답에 직면했습니다.
<script type="text/javascript">
var a = "{{someDjangoVariable}}"
</script>
그러나 여기서 중요한 구현 제한 사항 을 지적하고 싶습니다 . 자바 스크립트 코드를 다른 파일에 넣고 해당 파일을 템플릿에 포함시키려는 경우. 작동하지 않습니다.
메인 템플릿과 자바 스크립트 코드가 동일한 파일에있는 경우에만 작동합니다. 아마도 django 팀 이이 한계를 해결할 수 있습니다.
I've been struggling with this too. On the surface it seems that the above solutions should work. However, the django architecture requires that each html file has its own rendered variables (that is, {{contact}}
is rendered to contact.html
, while {{posts}}
goes to e.g. index.html
and so on). On the other hand, <script>
tags appear after the {%endblock%}
in base.html
from which contact.html
and index.html
inherit. This basically means that any solution including
<script type="text/javascript">
var myVar = "{{ myVar }}"
</script>
is bound to fail, because the variable and the script cannot co-exist in the same file.
The simple solution I eventually came up with, and worked for me, was to simply wrap the variable with a tag with id and later refer to it in the js file, like so:
// index.html
<div id="myvar">{{ myVar }}</div>
and then:
// somecode.js
var someVar = document.getElementById("myvar").innerHTML;
and just include <script src="static/js/somecode.js"></script>
in base.html
as usual. Of course this is only about getting the content. Regarding security, just follow the other answers.
For a JavaScript object stored in a Django field as text, which needs to again become a JavaScript object dynamically inserted into on-page script, you need to use both escapejs
and JSON.parse()
:
var CropOpts = JSON.parse("{{ profile.last_crop_coords|escapejs }}");
Django's escapejs
handles the quoting properly, and JSON.parse()
converts the string back into a JS object.
Note, that if you want to pass a variable to an external .js script then you need to precede your script tag with another script tag that declares a global variable.
<script type="text/javascript">
var myVar = "{{ myVar }}"
</script>
<script type="text/javascript" src="{% static "scripts/my_script.js" %}"></script>
data
is defined in the view as usual in the get_context_data
def get_context_data(self, *args, **kwargs):
context['myVar'] = True
return context
you can assemble the entire script where your array variable is declared in a string, as follows,
views.py
aaa = [41, 56, 25, 48, 72, 34, 12]
prueba = "<script>var data2 =["
for a in aaa:
aa = str(a)
prueba = prueba + "'" + aa + "',"
prueba = prueba + "];</script>"
that will generate a string as follows
prueba = "<script>var data2 =['41','56','25','48','72','34','12'];</script>"
after having this string, you must send it to the template
views.py
return render(request, 'example.html', {"prueba": prueba})
in the template you receive it and interpret it in a literary way as htm code, just before the javascript code where you need it, for example
template
{{ prueba|safe }}
and below that is the rest of your code, keep in mind that the variable to use in the example is data2
<script>
console.log(data2);
</script>
that way you will keep the type of data, which in this case is an arrangement
참고URL : https://stackoverflow.com/questions/298772/django-template-variables-and-javascript
'Programing' 카테고리의 다른 글
iOS 원격 디버깅 (0) | 2020.05.12 |
---|---|
요소 별 동일성을 위해 두 개의 numpy 배열 비교 (0) | 2020.05.12 |
SQL에서 무작위로 행을 선택하는 방법은 무엇입니까? (0) | 2020.05.11 |
Android 애플리케이션에서 현재 시간 및 날짜 표시 (0) | 2020.05.11 |
프로젝트 빌드 설정이 dSYM 파일을 생성하고 있는지 확인하십시오. (0) | 2020.05.11 |