filter

作者: Tsukinousag | 来源:发表于2022-12-30 23:51 被阅读0次

    直接调用filter

    //views.py
    from django.shortcuts import render
    from django.template import loader,Context
    from django.http import HttpResponse
    
    # Create your views here.
    
    def index(request):
        t=loader.get_template('index.html')
        list1=[3,5,9,8,4,6,10,-1,45,6]
        words='hello'
        mystring='hello django'
    
        return HttpResponse(t.render({
            'list':list1,
            'word':words,
            'str':mystring
        }))
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>index</title>
    </head>
    <body>
        <ul>
            <li>test first filter with {{list}}: {{ list | first }}</li>
            <li>test upper filter with {{word}}: {{ word | upper }}</li>
            <li>test capfirst filter with {{str}}: {{ str | capfirst }}</li>
        </ul>
    </body>
    </html>
    
    //myfilter.py
    from django import template
    
    #初始化
    register=template.Library()
    
    def myfilter(mylist):
        res=[]
        for value in mylist:
            if value>=5 and value<=10:
                res.append(value)
    
        return res
    
    ##注册
    register.filter(myfilter)
    

    最后是加载filter

    相关文章

      网友评论

          本文标题:filter

          本文链接:https://www.haomeiwen.com/subject/oratcdtx.html