【发布时间】:2020-01-15 09:00:33
【问题描述】:
我正在为导航栏中的活动/当前访问的链接放置一个模板标签,这样我就可以轻松地将适当的活动 CSS 类添加到链接中。
我创建的代码适用于包含相同 url 参数的传入 url 的混合,但它不允许我传入具有不同参数的 url。
{% make_active 'index' %} 和 {% make_active 'users' 1 %} 无法准确组合为 {% make_active 'index~users' 1 %},因为我正在使用 reverse() 来查看 url 是否存在。
我想要的只是检查项目中每个 url 模式文件的名称,如果名称存在,则返回适当的活动类……但我不知道如何简单地获取名称。这可能吗,或者有人可以帮助编写代码吗?
@register.simple_tag(takes_context=True)
def make_active(context, view_names, *args, **kwargs):
print(args, kwargs)
if not kwargs.pop('class', None):
class_to_return = 'sidebar-item-active'
else:
class_to_return = kwargs.pop('class')
request = context.get('request')
if not request:
raise Exception('A request must be passed in for this to work')
names = view_names.split('~')
print(names)
current_url_active = False
for view in names:
print(view)
try:
# always include the client url
args_to_use = [request.client_url]
# append the passed args into the args for reversing the url name
args_to_use.extend(args)
reversed_path = reverse(view, args=args_to_use)
print(reversed_path)
current_url_active = True
except NoReverseMatch:
current_url_active = False
continue
if current_url_active:
break
return class_to_return if current_url_active else None
【问题讨论】:
标签: django python-3.x django-templates