Django 自定义标签

1,简单标签

1.1 添加自定义标签函数

Test/app5/templatetags/mytags.py

from django import template
register = template.Library()
@register.simple_tag()
def show_title(value, n):
    if len(value) > n:
        return f'{value[:n]}...'
    else:
        return value

1.2 添加视图函数

from django.shortcuts import render

# Create your views here.
import datetime

def filter(request):
    str1 = 'abcdefg'
    str2 = 'ABCDEFGHIJKLMNO'
    str3 = '123456789'

    time_str = datetime.datetime.now()
    return render(request, '5/filter.html', {'str1':str1, 'str2':str2, 'str3':str3, 'time_str':time_str})


def html_filter(request):
    html_addr = """
        <table border='2'>
            <tr>
                <td>
                这是表格A
                </td>
                <td>
                这是表格B
                </td>
            </tr>
        </table>
    """

    html_script = """
        <script language='JavaScript'>
            document.write('非法执行');
        </script>
    """

    return render(request, '5/html_filter.html', {"html_addr":html_addr, "html_script":html_script})


def diy_filter(request):
    dict1 = {'标题': '学习Django天天加班,熬到深夜,沉迷学习无法自拔!'}
    dict2 = {'标题': '学习java天天加班,熬到深夜,沉迷学习无法自拔!'}
    dict3 = {'标题': '学习C++天天加班,熬到深夜,沉迷学习无法自拔!'}
    lists = [dict1, dict2, dict3]
    return render(request, '5/diy_filter.html', {"lists":lists})

def diy_tags(request):
    dict1 = {'标题': '学习Django天天加班,熬到深夜,沉迷学习无法自拔!'}
    dict2 = {'标题': '学习java天天加班,熬到深夜,沉迷学习无法自拔!'}
    dict3 = {'标题': '学习C++天天加班,熬到深夜,沉迷学习无法自拔!'}
    lists = [dict1, dict2, dict3]
    return render(request, '5/diy_tags.html', {"lists":lists})

1.3 添加路由地址

Test/app5/urls.py

from django.urls import path
from . import views


urlpatterns = [
    path('filter', views.filter, name='filter'),
    path('html_filter', views.html_filter, name='html_filter'),
    path('diy_filter', views.diy_filter, name='diy_filter'),
    path('diy_tags', views.diy_tags, name='diy_tags'),
]

1.4 添加html代码

Test/templates/5/diy_tags.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

{% load mytags %} <!-- 使用半角字符 -->
<table border="1" style="width: 300px">
    {% for list in lists %}
    <tr>
        <td>
            {% show_title list.标题 10 %}
        </td>
    </tr>
    {% endfor %}
</table>

</body>
</html>

1.5 访问页面

http://127.0.0.1:8000/app5/diy_tags

2,包含标签

2.1 添加自定义标签函数

Test/app5/templatetags/mytags.py

from django import template
register = template.Library()
@register.simple_tag()
def show_title(value, n):
    if len(value) > n:
        return f'{value[:n]}...'
    else:
        return value



@register.inclusion_tag("5/show_info_tags2.html")
def show_info_tags2():
    dict1={'标题':'小强|2024-06-29'}
    dict2={'标题':'小强|2024-06-29'}
    dict3={'标题':'小强|2024-06-29'}
    lists=[dict1,dict2,dict3]
    return {'lists':lists}

2.2 添加html代码

Test/templates/5/show_info_tags2.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<table border="1" style="width: 310px">
  {% for list in lists %}
    <tr>
      <td>
        {{ list.标题 }}
      </td>
    </tr>

  {% endfor %}
</table>

</body>
</html>

2.3 添加视图函数

Test/app5/views.py

from django.shortcuts import render

# Create your views here.
import datetime

def filter(request):
    str1 = 'abcdefg'
    str2 = 'ABCDEFGHIJKLMNO'
    str3 = '123456789'

    time_str = datetime.datetime.now()
    return render(request, '5/filter.html', {'str1':str1, 'str2':str2, 'str3':str3, 'time_str':time_str})


def html_filter(request):
    html_addr = """
        <table border='2'>
            <tr>
                <td>
                这是表格A
                </td>
                <td>
                这是表格B
                </td>
            </tr>
        </table>
    """

    html_script = """
        <script language='JavaScript'>
            document.write('非法执行');
        </script>
    """

    return render(request, '5/html_filter.html', {"html_addr":html_addr, "html_script":html_script})


def diy_filter(request):
    dict1 = {'标题': '学习Django天天加班,熬到深夜,沉迷学习无法自拔!'}
    dict2 = {'标题': '学习java天天加班,熬到深夜,沉迷学习无法自拔!'}
    dict3 = {'标题': '学习C++天天加班,熬到深夜,沉迷学习无法自拔!'}
    lists = [dict1, dict2, dict3]
    return render(request, '5/diy_filter.html', {"lists":lists})

def diy_tags(request):
    dict1 = {'标题': '学习Django天天加班,熬到深夜,沉迷学习无法自拔!'}
    dict2 = {'标题': '学习java天天加班,熬到深夜,沉迷学习无法自拔!'}
    dict3 = {'标题': '学习C++天天加班,熬到深夜,沉迷学习无法自拔!'}
    lists = [dict1, dict2, dict3]
    return render(request, '5/diy_tags.html', {"lists":lists})

def show_info_2(request):
    return render(request, '5/show_info_2.html')

2.4 添加html代码

Test/templates/5/show_info_2.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

{% load mytags %}
<p>当前文件是show_info_2</p>
<p>以下内容是从另外一个模版文件show_info_tags2加载的</p>
{% show_info_tags2 %}
</body>
</html>

2.5 添加路由地址

Test/app5/urls.py

from django.urls import path
from . import views


urlpatterns = [
    path('filter', views.filter, name='filter'),
    path('html_filter', views.html_filter, name='html_filter'),
    path('diy_filter', views.diy_filter, name='diy_filter'),
    path('diy_tags', views.diy_tags, name='diy_tags'),
    path('show_info_2', views.show_info_2, name='show_info_2'),

]

2.6 访问页面

http://127.0.0.1:8000/app5/show_info_2

相关推荐
大写-凌祁1 分钟前
基于遥感与通信技术的灾害应急测绘
python
麦田里的稻草人w6 分钟前
【YOLO】(基础篇一)YOLO介绍
人工智能·python·神经网络·yolo·机器学习
Bruce_Liuxiaowei8 分钟前
Python编程构建动态的圣诞画面
开发语言·python
wang_yb15 分钟前
Python包管理不再头疼:uv工具快速上手
python·databook
山川而川-R40 分钟前
ubuntu22.04安装PaddleX3
python·ocr
从以前1 小时前
【算法题解】Bindian 山丘信号问题(E. Bindian Signaling)
开发语言·python·算法
海绵波波1072 小时前
flask后端开发(9):ORM模型外键+迁移ORM模型
后端·python·flask
余生H2 小时前
前端Python应用指南(二)深入Flask:理解Flask的应用结构与模块化设计
前端·后端·python·flask·全栈
CriticalThinking2 小时前
Pycharm不正常识别包含中文路径的解释器
ide·python·pycharm