【问题标题】:Add active class to element according to URL Jquery Django根据URL Jquery Django将活动类添加到元素
【发布时间】:2015-08-05 09:54:39
【问题描述】:

如何根据 href 向元素添加“活动”类

我有一个这样的 django 模板:

<div class="panel side-panel-1 category">
<h4 class="title1">Разделы</h4>
<ul class="clear-list">
{% for section in sections %}
    <li>
        <a href="/advert/adverts.aspx&sec{{ section.id }}">{{ section.name }}  ({{ section.advert_set.count }})</a>
    </li>
{% endfor %}
</ul>

所以 url 将由 section.id 形成

示例:

  • mysite.com/advert/adverts.aspx&sec1

在某些情况下可能是:

  • mysite.com/advert/adverts.aspx&sec1&cat10&page1

【问题讨论】:

  • 当你想在元素上添加活动类时?据我所知,您可以使用 django 调节本身来处理它。
  • 我不知道django中的这个功能。如果你可以回答它
  • 我的意思是只使用正常的 if 条件来检查 href 并在条件满足时添加活动类。参考:stackoverflow.com/questions/5584426/…
  • @Prasad 我看到了这个问题,但我无法在我的情况下实现它,你能帮我吗?

标签: jquery css django


【解决方案1】:

也许你想这样做。只能使用class="{{ section.id ? 'active' : '' }}"。如果 section.id 存在,则添加活跃的。

<div class="panel side-panel-1 category">
<h4 class="title1">Разделы</h4>
<ul class="clear-list">
{% for section in sections %}
    <li class="{{ section.id ? 'active' : '' }}" >
        <a href="/advert/adverts.aspx&sec{{ section.id }}">{{     section.name }}  ({{ section.advert_set.count }})</a>
   </li>
{% endfor %}
</ul>

【讨论】:

  • TemplateSyntaxError at /advert/adverts.aspx 无法解析剩余部分:' ? '活动' : ''' 来自 'section.id ? '活跃' : '''
  • 抱歉,python 没有'?'手术。你可以改成'active' if section.id else ''
  • 无法解析剩余部分:' if section.id else ''' from ''active' if section.id else '''
【解决方案2】:

在views.py中

def adverts_sec(request, advert_sec):
args = {}
args.update(csrf(request))
args['adverts'] =  Advert.objects.filter(advert_section_id=advert_sec).order_by('-advert_date', '-id')
args['sections'] = AdvertSection.objects.all().order_by('-name')
args['categs'] = AdvertCategory.objects.all().order_by('-name')
args['current_section'] = AdvertSection.objects.get(id=advert_sec)
args['username'] = auth.get_user(request).username
args['reg_form'] = MyRegistrationForm()
return render_to_response('adverts_sec.html', args)

然后在模板中:

{% for section in sections %}
    <li class="{% if section.id == current_section.id %}
                    active
                {% else %}
                {% endif %}">
        <a href="/advert/adverts.aspx&sec{{ section.id }}">{{ section.name }}  ({{ section.advert_set.count }})</a>
    </li>
{% endfor %}

所以如果我们有“current_section”,那么 django 将其与 {{ section.id }} 进行比较,匹配的将获得一个“活动”类

感谢每一位帮助过我的人

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-24
    • 2023-01-22
    • 2019-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多