04_Django-模板变量/标签/过滤器/继承-url反向解析

博客🔗:https://blog.youkuaiyun.com/cPen_web
视频🔗:https://www.bilibili.com/video/BV1vK4y1o7jH


变量和标签

变量

  • 视图函数中可以将Python变量封装到 字典 中传递到模板上

样例:

def xxx_view(request):
    dic = {
   
   
        "变量1": "值1",
        "变量2": "值2",
    }
    return render(request, 'xxx.html', dic)
  • 能传递到模板中的 数据类型
str-字符串	int-整型
list-数组	tuple-元组
dict-字典	func-方法
obj-类实例化的对象
  • 在模板中使用变量语法
- {
  
  { 变量名 }}
- {
  
  { 变量名.index }}
- {
  
  { 变量名.key }}
- {
  
  { 对象.方法 }}
- {
  
  { 函数名 }}
  • 演示:
http://127.0.0.1:8000/test_html_param

image-20220216013835514

# mysite1/mysite1/urls.py
urlpatterns = [
    ...
    path('test_html', views.test_html)
]


# mysite1/mysite1/views.py
def test_html_param(request):
    dic = {
   
   }
    dic['int'] = 88
    dic['str'] = 'peng'
    dic['lst'] = ['Tom', 'Jack', 'Lily']
    dic['dict'] = {
   
   'a':9, 'b':8}
    dic['func'] = say_hi
    dic['class_obj'] = Dog()
    dic['script'] = '<script>alert(1111)</script>'
    return render(request, 'test_html_param.html', dic)

def say_hi():
    return 'hahaha'

class Dog:
    def say(self):
        return 'wangwang'


# mysite1/templates/test_html_param.html
<h3>int{
   
   {
   
    int|add:"2" }}</h3>
<h3>str{
   
   {
   
    str|upper }}</h3>
<h3>lst 是 {
   
   {
   
    lst }}</h3>
<h3>lst 是 {
   
   {
   
    lst.0 }}</h3>
<h3>dict{
   
   {
   
    dict }}</h3>
<h3>dict['a']{
   
   {
   
    dict.a }}</h3>
<h3>function 是 {
   
   {
   
    func }}</h3>
<h3>class_obj 是 {
   
   {
   
    class_obj.say }}</h3>
<h3>script 是 {
   
   {
   
    script|safe }}</h3>

标签

模板标签

  • 作用:将一些服务器端的功能嵌入到模板中,例如流程控制等
  • 标签语法:
{% 标签 %}
...
{% 结束标签 %}

if标签

  • 语法
{% if 条件表达式1 %}
...
{% elif 条件表达式2 %}
...
{% elif 条件表达式3 %}
...
{% else %}
...
{% endif %}	- 需要有结束标签
  • 注意
  1. if条件表达式里可以用的运算符 ==, !=, <, > , <=, >=, in, not in, is, is not, not、and、or
  2. 在if标记中使用实际括号是无效的语法。如果需要它们指示优先级,则应使用嵌套的if标记。

官方文档:https://docs.djangoproject.com/zh-hans/2.2/ref/templates/builtins/#if

  • 演示:
http://127.0.0.1:8000/test_if_for

image-20220216020405259

# mysite1/mysite1/urls.py
urlpatterns = [
    ...
    path('test_if_for', views.test_if_for),
]

# mysite1/mysite1/views.py
def test_if_for(request):
    dic = {
   
   }
    dic['x'] = 20
    dic['lst'] = [
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mycpen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值