在Python中Django的模板渲染中出現的錯誤。如下是原因及解決方案。
原因:
views.py
from __future__ import unicode_literals
from django.shortcuts import render
def home(request):
List = ['自強學堂', '渲染Json到模板']
return render(request, 'home.html', {'List': List})
HTML中
<script type="text/javascript">
var List = {{ List }};
alert(List);
</script>
需要注意的是,我們如果直接這麼做,傳遞到 js 的時候,網頁的內容會被轉義,得到的格式會報錯。
訪問時會得到 Uncaught SyntaxError: Unexpected token ILLEGAL
解決辦法:
1. 視圖函數中的字典或列表要用 json.dumps()處理。
2. 在模板上要加 safe 過濾器。
views.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | # -*- coding: utf-8 -*- from __future__ import unicode_literals import json from django.shortcuts import render def home(request): List = [ '自強學堂' , '渲染Json到模板' ] Dict = { 'site' : '自強學堂' , 'author' : '塗偉忠' } return render(request, 'home.html' , { 'List' : json.dumps( List ), 'Dict' : json.dumps( Dict ) }) |
home.html 只給出了 js 核心部分:
1 2 3 4 | //列表 var List = {{ List|safe }}; //字典 var Dict = {{ Dict|safe }}; |