我想编写一个自定义url模板标签,它也适用于相对路径(而不仅仅是命名模式)并接受参数中的列表(后来用于调用不同的视图函数 - 这就是我需要请求对象的原因)。这是我在模板中的标记:
{% with '/views' (normally it's a var created in for loop) as link %}
<a href="{% url_for link params=('website','homepage') %}">Click</a>
{% endwith %}
和标记代码本身:
@register.simple_tag(takes_context = True)
def url_for(context, parser, token):
request = context['request']
bits = token.split_contents()
if len(bits) < 2:
raise TemplateSyntaxError("'%s' takes at least one argument"
" (path to a view)" % bits[0])
try:
if "/" in bits[1]:
bits[1] = unicodedata.normalize('NFKD', bits[1]).encode('utf-8', 'ignore')
try:
bits[1] = resolve(bits[1].replace("'","")).url_name
except Exception as e:
log.error('Exception when resolving url for tag: %s' % e)
viewname = bits[1]
except Exception as exc:
raise
args = []
kwargs = {}
asvar = None
bits = bits[2:]
if len(bits):
for bit in bits:
if 'params' in bit:
par = ast.literal_eval(bit.split('=')[1])
my_function(request, par[0], par[1])
break
from django.core.urlresolvers import reverse, NoReverseMatch
url = ''
try:
url = reverse(viewname, args=args, kwargs=kwargs, current_app=context.current_app)
except NoReverseMatch:
exc_info = sys.exc_info()
if settings.SETTINGS_MODULE:
project_name = settings.SETTINGS_MODULE.split('.')[0]
try:
url = reverse(project_name + '.' + view_name,
args=args, kwargs=kwargs,
current_app=context.current_app)
except NoReverseMatch:
six.reraise(*exc_info)
else:
raise
return url
不幸的是,我现在唯一能做到的就是TemplateSyntaxError at /: Could not parse the remainder: '('website','homepage')' from '('website','homepage')'
。在此之前,我试图monkeypatch原始的url标记和URLNode但我有一堆不同的问题。任何有助于解决此问题的帮助。
答案 0 :(得分:1)
模板文件不是Python。因此,你不能用你的论点做元组事。相反,重构模板标记以采用这种语法:
{% url_for link params='website homepage' %}
然后,在解析模板标记中的bits
变量时,您必须考虑到这一点。
它最终归结为解析字符串。
https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-the-compilation-function
请参阅“token.contents”和“token.split_contents()”的注释。