<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>编码