django 的模板裏面變量取值是經過句點語法來取值,就是一個點(.)符號。取值的對象也能夠是字符串,int類型,list列表,字典鍵值對,也能夠是一個類的實例對象。html
好比我在 views.py 視圖函數定義了一些不一樣類型的變量python
from django.shortcuts import render from django.http import HttpResponse # Create your views here. from django.http import JsonResponse from django.shortcuts import render # 上海悠悠,QQ交流羣:750815713 def personalView(request): context = { "name": "上海-悠悠", "n_name": "悠悠", "age": 20, "fancy": ["python", "django", "pytest"], "blog": { "url": "https://www.cnblogs.com/yoyoketang/", "img": "https://pic.cnblogs.com/avatar/1070438/20161126151035.png" } } class Myblog(): def __init__(self): self.name = "上海-悠悠" self.age = 20 def guanzhu(self): return 100 def fensi(self): return 1000 myblog = Myblog() # 實例 context["myblog"] = myblog return render(request, "personal.html", context=context)
在 templates 目錄下新建一個 personal.html 模板django
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="referrer" content="no-referrer" /> <title>Title</title> </head> <body> <div> <h1 class="display_name">{{ name }}</h1> <div> <p class="text_gray"><span>姓名: </span>{{ n_name }}</p> <p class="text_gray"><span>年齡:</span>{{ age }}</p> <p class="text_gray"><span>感興趣的技術:</span>{{ fancy.0 }}、{{ fancy.1 }}、{{ fancy.2 }}</p> </div> </div> <h1 class="display_name">經過字典對象取值</h1> <div> <p class="text_gray"><span>博客地址: </span> <a href="{{ blog.url }}"> {{ blog.url }} </a> </p> <p class="text_gray"><span>頭像</span> <img src="{{ blog.img }}"> </p> </div> <h1 class="display_name">經過屬性、方法取值</h1> <p class="text_gray"><span>名稱: </span>{{ myblog.name }}</p> <p class="text_gray"><span>關注數: </span>{{ myblog.guanzhu }}</p> <p class="text_gray"><span>粉絲數:</span>{{ myblog.fensi }}</p> </body> </html>
最終顯示效果以下函數