• Django模板变量的使用


       在views.py中进行逻辑控制,编写向跳转页面传递内容的代码。可以看出,对类、字典、列表中的数据均可操作。views.py的内容如下:

     1 from django.shortcuts import render
     2 from django.http import HttpResponse
     3 # Create your views here.
     4 user_list = [
     5     {'name': 'xiao wang', 'age': '18'},
     6     {'name': 'hua hua', 'age': '20'}
     7 ]
     8 # user = {'name': 'hua hua', 'age': '20', 'sex': 'male'}
     9 class Person(object):
    10     def __init__(self, name, age, sex):
    11         self.name = name
    12         self.age = age
    13         self.sex = sex
    14 
    15     def say(self):
    16         return 'I am ' + self.name
    17 user = Person('Tom', 23, 'male')
    18 book_list = ['python', 'java', 'php']
    19 
    20 def say(request):
    21     return render(request, 'index.html', {'title': 'my page', 'user': user, 'book_list': book_list})

      在templates下的index.html文件内容。其中,模板变量用{{}}表示。

     1 <!DOCTYPE html>
     2 <html lang="en">
     3 <head>
     4     <meta charset="UTF-8">
     5     <title>hello</title>
     6 </head>
     7 <body>
     8 <h1>hello {{ user.name }}</h1>
     9 <li>age:{{ user.age }}</li>
    10 <li>sex:{{ user.sex }}</li>
    11 <div>the {{ user.name }} sya: {{ user.say }}</div>
    12 {{ book_list.0 }}
    13 </body>
    14 </html>

      访问页面:127.0.0.1:8000/index/,页面显示:

  • 相关阅读:
    Keep at Most 100 Characters
    Larry and Inversions
    计算指数
    简单题
    重要的话说三遍
    I Love GPLT
    猜数字
    打印沙漏
    多态性(polymorphism),封装性(encapsulation),内聚(cohesion)以及耦合(coupling)的基本概念
    Hibernate面试题
  • 原文地址:https://www.cnblogs.com/demo-deng/p/7757800.html
Copyright © 2020-2023  润新知