zoukankan      html  css  js  c++  java
  • 第十九节 模板变量

    1)当传入对象是类实例时,通过 键.类属性 的形式在HTML中调用,view.py代码如下

    1 class Person():
    2     username='李四'
    3 
    4 def index(request):
    5     p = Person()
    6     context = {
    7         'username':p
    8     }
    9     return render(request, 'index.html', context=context)

    index.html 代码如下

     1 <!DOCTYPE html>
     2 <html lang="en">
     3 <head>
     4     <meta charset="UTF-8">
     5     <title>模板渲染</title>
     6 </head>
     7 <body>
     8     {{ username.username }}
     9 </body>
    10 </html>

    2)当传入对象是字典时,view.py代码如下

    1 def index(request):
    2     context = {
    3         'username':'李梅'
    4     }
    5     return render(request, 'index.html', context=context)

    index.html 代码如下

     1 <!DOCTYPE html>
     2 <html lang="en">
     3 <head>
     4     <meta charset="UTF-8">
     5     <title>模板渲染</title>
     6 </head>
     7 <body>
     8     {{ username }}
     9 </body>
    10 </html>

    3)当传入是嵌套字典时,view.py代码如下

    1 def index(request):
    2     context = {
    3         'username':{
    4             'first':'张三',
    5             'second':'李四',
    6             'keys':'王五'
    7         }
    8     }
    9     return render(request, 'index.html', context=context)

    index.html 代码如下

     1 <!DOCTYPE html>
     2 <html lang="en">
     3 <head>
     4     <meta charset="UTF-8">
     5     <title>模板渲染</title>
     6 </head>
     7 <body>
     8     {{ username.first }}
     9 </body>
    10 </html>

    4)当传入的是列表或者元组时,两种的用法一样,view.py代码如下

    1 def index(request):
    2     context = {
    3         'username':['lisi','caocao','huangzhong','likui']
    4     }
    5     return render(request, 'index.html', context=context)

    index.html 代码如下

     1 <!DOCTYPE html>
     2 <html lang="en">
     3 <head>
     4     <meta charset="UTF-8">
     5     <title>模板渲染</title>
     6 </head>
     7 <body>
     8     {{ username.0 }}
     9     {{ username.1}}
    10 </body>
    11 </html>
  • 相关阅读:
    shell脚本day06-sed
    shell脚本day05-交互式输入与for语句
    shell脚本day04-if语句
    shell脚本day04-grep与正则表达式
    shell脚本day03-编程原理
    shell脚本day02-重定向与管道符
    编程原理大致介绍
    进程管理
    Linux网络
    shell脚本--grep以及正则表达式
  • 原文地址:https://www.cnblogs.com/kogmaw/p/12444745.html
Copyright © 2011-2022 走看看