깔끔하게 직렬화 미리로드 분리하는 방법이 있습니다 도움이 escapejs
var data = '{{data|escapejs}}';
희망을 사용하여 템플릿을 렌더링하기 전에 data
를 청소 수 나머지 코드의 데이터
예 1 테이블 성분에서 사용 후에 window
에서 전역 변수에 프리로드 데이터 -assigning하고 :
<html>
<meta charset="utf-8">
<body>
<script>
// Loading the data for use in JS components here
(function() {
window.tableData = JSON.parse('{{ table_data }}');
}());
</script>
<script src="table.js"></script>
<!-- table.js uses window.tableData when building the table -->
</body>
예 2 -encapsulate 테이블 요소를 모듈로에서 초기화 기본 템플릿을 수정하고 미리로드 된 데이터를 전달합니다.
<html>
<meta charset="utf-8">
<body>
<table id="theTable"></table>
<script src="table.js"></script>
<!-- table.js exports itself globally as window.table -->
<script>
// Loading the data and initializing table component
(function() {
var tableEl = $('#theTable');
var tableData = JSON.parse('{{ table_data }}');
window.table.init(tableData, tableEl);
}());
</script>
</body>
기타 등등!
Django 템플릿 언어와 JavaScript가 섞이지 않도록하고 싶습니까?
- XHR을 통해 모든 데이터를 전달하면 페이지가로드 된 후 서버에 AJAX 요청이 전송됩니다. JavaScript에서 구문 분석하기 쉬운 JSON으로 필요한 데이터를 반환하는 Django 뷰를 작성한다.
데이터를 가져올 장고 템플릿 언어 밖으로 및 피할 추가 XHR이 모든 것을이-유지 원하십니까?
- React.js 또는 AngularJS와 같은 프레임 워크에서 응용 프로그램을 빌드하고 구성 요소의 서버 측 렌더링을 활용하십시오.
{{data}} - json 데이터입니까? http://stackoverflow.com/questions/38620816/django-passing-json-data-to-static-getjson-javascript/38621448 – Igor
가능한 [Django 템플릿 변수 및 자바 스크립트] 복제본 (http://stackoverflow.com/questions)/298772/django-template-variables-and-javascript) – Cory