<html> <head> <meta charset='UTF-8'><meta name='viewport' content='width=device-width initial-scale=1'> <title>django之自定義標籤</title></head> <body><h1>django之自定義標籤</h1> <h2>自定義標籤建立</h2> <ol> <li>在應用文件夾下建立templatetags文件夾</li> <li>在文件夾下建立py腳本,如mytags.py</li> <li>在mytags.py寫入自定義標籤的處理代碼</li>html
</ol> <pre><code class='language-python' lang='python'>#自定義標籤傳參後,攜帶原路徑參數或跳轉路徑的獲取數據參數 #自定義標籤 from django import template from django.urls import reverse前端
register = template.Library()python
@register.simple_tag def resolve_url(request,url_name,cid): """django
:param request: 請求對象 :param url_name: url別名 :param cid: 客戶id :return: """ from django.http.request import QueryDict custom_query_dict = QueryDict(mutable=True) custom_query_dict['next'] = request.get_full_path() #要跳轉回的url next_url = custom_query_dict.urlencode() #將獲得的搜索路徑url編碼 reverse_url = reverse(url_name,args=(cid,)) #編輯的url ?next=要跳轉的url full_path = reverse_url + '?' + next_url return full_path
</code></pre>後端
<p>在前端頁面中,數據傳參</p> <pre><code class='language-html' lang='html'><a href="{{ resolve_url request "case_edit" foo.id }}"></a> </code></pre> <p>後端view視圖</p> <pre><code class='language-python' lang='python'>from django.shortcuts import render,redirect,HttpResponse, next_url = request.GET.get("next") return redirect(next_url) </code></pre> <p> </p> </body> </html>編碼