zoukankan      html  css  js  c++  java
  • Python

    自定义过滤器的文件:

    在 app01 下新建一个 templatetags 的文件夹,然后创建 myfilter.py 文件

    这个 templatetags 名字是固定的,myfilter 是自己起的

    myfilter.py:

    from django import template
    register = template.Library()
    
    
    @register.filter(name="sleep")  # name 是 html 中的过滤器名
    def sleep(arg):
        return "%s is sleep" %arg
    

    views.py:

    from django.shortcuts import render, redirect, HttpResponse
    from app01 import models
    
    
    # Filter 测试
    def filter_test(request):
        name = "Jack"
        return render(request, "filter_test.html", {"name": name})
    

    filter_test.html:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Filter 测试</title>
    </head>
    <body>
    
    <!-- 这里需要导入自定义的 filter --> {% load myfilter %} {{ name|sleep }} </body> </html>

     运行结果:

    定义含参数的 filter:

    myfilter.py:

    from django import template
    register = template.Library()
    
    
    @register.filter(name="sleep")
    def sleep(arg):
        return "%s is sleep" %arg
    
    
    @register.filter(name="eat")
    def eat(arg, arg1):
        return "%s is eating %s" %(arg, arg1)
    

    filter_test.html:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Filter 测试</title>
    </head>
    <body>
    
    {% load myfilter %}
    {{ name|sleep }}
    <br>
    {{ name|eat:"meat" }}
    
    </body>
    </html>
    

    运行结果:

  • 相关阅读:
    CodeForces 670E Correct Bracket Sequence Editor
    CodeForces 670F Restore a Number
    HDU 5895 Mathematician QSC
    HDU 5880 Family View
    HDU 5886 Tower Defence
    CSS3.16
    CSS页面定制代码+动漫人物设计
    TSP变形(三进制状压)
    三进制状压(涂抹果酱)
    最小点覆盖(König定理)
  • 原文地址:https://www.cnblogs.com/sch01ar/p/11252815.html
Copyright © 2011-2022 走看看