django神器 <自定義過濾器filter 和 標籤tag>

自定義過濾器filter和標籤tag

  • filter 自定義過濾器html

    • 建立python

      1. 在app下建立一個名爲templatetags的python包(名稱不能變)django

      2. 在templatetags 建立py文件 自定義名稱 my_tags.py(名稱自定義)app

      3. 在py文件中寫入:函數

        from django import template
        
        register = template.Library()  # register也不能變
      4. 寫函數+裝飾器ui

        @register.filter
        def add_xx(value, arg):  # 最多有兩個
        
            return '{}-{}'.format(value, arg)
    • 使用
      1. 使用code

        {% load my_tags %}
        {{ 'alex'|add_xx:'dsb' }}
  • simpletag 標籤(返回內容自定義)orm

    • 和自定義filter相似,只不過接收更靈活的參數。htm

    • 定義註冊simple tagit

      @register.simple_tag(name="plus")
      def plus(a, b, c):
          return "{} + {} + {}".format(a, b, c)
    • 使用自定義simple tag

      {% load app01_demo %}
      
      {# simple tag #}
      {% plus "1" "2" "abc" %}
  • inclusion_tag 標籤(函數內返回內容必須是一個字典,第三個文件去渲染,而後代碼段返回給html文件)

    示例:

    1. templatetags/my_inclusion.py
    from django import template
    
    register = template.Library()
    
    
    @register.inclusion_tag('result.html')
    def show_results(n):
        n = 1 if n < 1 else int(n)
        data = ["第{}項".format(i) for i in range(1, n+1)]
        return {"data": data}
    1. templates/result.html
    <ul>
      {% for choice in data %}
        <li>{{ choice }}</li>
      {% endfor %}
    </ul>
    1. templates/index.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta http-equiv="x-ua-compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>inclusion_tag test</title>
    </head>
    <body>
    
    {% load my_inclusion %}
    
    {% show_results 10 %}
    </body>
    </html>
相關文章
相關標籤/搜索