Django 自定义标签“takes_context”
我是 django 的新手(来自 Grails),尤其是您必须处理的所有自定义标签,而不是直接在模板中写入变量。
好吧,我需要做的事情非常简单,但由于某种原因花了我很长时间才能完成。我想做的是创建一个标签来检查给定路径是否等于我当前的 url,然后如果为真则返回该类。
<li class="{% check_url '/login/' 'current_page_item' %}">
<a href="{% url social_login %}">login</a>
</li>
但是,当我尝试使用 Takes_context 注册标签时,问题出现了:
渲染时捕获 TypeError:simple_tag() 得到意外的关键字参数 'takes_context'
from django import template
register = template.Library()
@register.simple_tag(takes_context=True)
def check_url(context, path, attr):
if context['request'].environ.get('PATH_INFO') == path:
return attr
else:
return ''
我该如何修复它?另外,有更好的方法吗?
I`m new with django (came from Grails), especially with all those custom tags that you have to deal with, instead of writing your variables directly inside the templates.
Well, what I need to do was something really simple, but for some reason is taking me a long time to finish. What I wish to do was make a tag that checks for me if the given path is equals my current url, and then returns the class if true.
<li class="{% check_url '/login/' 'current_page_item' %}">
<a href="{% url social_login %}">login</a>
</li>
But, the problem came when I tried to register the tag with takes_context :
Caught TypeError while rendering: simple_tag() got an unexpected keyword argument 'takes_context'
from django import template
register = template.Library()
@register.simple_tag(takes_context=True)
def check_url(context, path, attr):
if context['request'].environ.get('PATH_INFO') == path:
return attr
else:
return ''
How can I fix it? Also, is there a better way to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是因为
takes_context
仅自 django 1.3 起可用。That's because
takes_context
is only available since django 1.3.另一种方法(并避免硬编码的网址):
或者查看类似 这个!
Another approach to do it (and to avoid hardcoded urls):
Or check out something like this!