根据https://docs.djangoproject.com/en/2.0/ref/templates/builtins/#url,可以定义一个稍后要检索的URL,如下所示:
{% url 'some-url-name' arg arg2 as the_url %}
<a href="{{ the_url }}">I'm linking to {{ the_url }}</a>
关注https://simpleisbetterthancomplex.com/snippet/2016/08/22/dealing-with-querystring-parameters.html后,我定义了一个标记relative_url
,如下所示:
from django import template
from django.utils.http import urlencode
from django.http import QueryDict
register = template.Library()
@register.simple_tag
def relative_url(field_name, value, query_string=None):
url = urlencode({field_name: value})
if query_string:
query_dict = QueryDict(query_string, mutable=True)
query_dict[field_name] = value
url = query_dict.urlencode()
return '?' + url
我想将此标记与as
一起使用,类似于内置的url
标记,以便我可以
{% with params=request.GET.urlencode %}
{% relative_url field value params as action_url %}
{% endwith %}
然后将其称为
<form action="{{ action_url }}"> ... </form>
我正在https://github.com/django/django/blob/master/django/template/defaulttags.py查看url
标记的Django源代码,但我发现它并不容易理解。
我怀疑我需要做的不是返回字符串,而是返回URLNode
,如
return URLNode(viewname, args, kwargs, asvar)
其中asvar
是注入上下文的变量,但我不确定要为每个构造函数参数填写什么。在此示例中是否有一种将变量注入上下文的简单方法?
答案 0 :(得分:1)
您实际上不需要做任何事情:此功能内置于simple_tag
装饰器中。只需按照您在该示例中显示的方式使用它。
请参阅文档simple_tag
section的最后一段。