获取模板中的当前URL kwargs?

时间:2014-07-19 20:51:34

标签: django django-templates django-urls

我现在正在通过以下方式完成此任务:

    context['card_type'] = self.kwargs['card_type']
    context['role_line'] = self.kwargs['role_line']
    context['sort_by'] = self.kwargs['sort_by']

这对我来说似乎很直观。

说我是否已经在players/one/two/three

的网址

是否有一种预先构建的方法可以获取one, two & three的当前kwargs用于模板?

修改

urls.py

urlpatterns = patterns('',
                   url(
                       r'^$',
                       NationListView.as_view(),
                       name='index'
                   ),
                   url(
                       r'^(?P<slug>[a-z-]*)/$',
                       NationDetailView.as_view(),
                       name='nation'
                   ),
                   url(
                       r'^(?P<slug>[a-z-]*)/(?P<card_type>[a-z]*)/(?P<role_line>[a-z]*)/(?P<sort_by>[a-z0-9]*)/$',
                       NationDetailFilteredView.as_view(),
                       name='nation_filter'
                   ),
                   )

构建上下文的mixin

class CoreDetailFilteredMixin(object):

    def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super(CoreDetailFilteredMixin, self).get_context_data(**kwargs)

        base_objects(context)
        # Pull all the players that belong to the object_type
        context['players'] = Player.objects.filter(
            **{filters: context['object'].asset_id}
        )

        # Define the available card types
        card_types = {
            'if': {'card_type__gte': 2},
            'gold': {'overall_rating__gte': 75},
            'silver': {'overall_rating__range': (65, 74)},
            'bronze': {'overall_rating__lte': 64}
        }
        # Check if the given card type is in the dictionary because 'all' throws an KeyError
        if self.kwargs['card_type'] in card_types:
            context['players'] = context['players'].filter(**card_types[self.kwargs['card_type']])

        # Don't show inform cards for specific colour card types
        if self.kwargs['card_type'] not in ['if', 'all']:
            context['players'] = context['players'].exclude(card_type__gte=2)

        # Define available role lines
        role_lines = {
            'att': 3,
            'mid': 2,
            'def': 1,
            'gk': 0
        }
        # Check if the given role line is in the dictionary because 'all' throws an KeyError
        if self.kwargs['role_line'] in role_lines:
            context['players'] = context['players'].filter(role_line=role_lines[self.kwargs['role_line']])

        # Define the available sort by keys
        sorts = {
            'ovr': 'overall_rating',
            'att1': 'card_att1',
            'att2': 'card_att2',
            'att3': 'card_att3',
            'att4': 'card_att4',
            'att5': 'card_att5',
            'att6': 'card_att6r'
        }
        # Add a descending order to the existing queryset
        context['players'] = context['players'].order_by('-' + sorts[self.kwargs['sort_by']])

        # Create pagination
        cbv_pagination(self, context, context['players'], 28, 'players')

        context['card_type'] = self.kwargs['card_type']
        context['role_line'] = self.kwargs['role_line']
        context['sort_by'] = self.kwargs['sort_by']

        return context

我目前如何在模板中使用

{% with object.get_class_name|add:'s'|add:':'|add:object.get_class_name|add:'_filter'|lower as url_string %}

<dl class="sub-nav">
  <dt>Card Type:</dt>
  {% with 'all if gold silver bronze' as card_types  %}
    {% for ct in card_types.split %}
      {% cycle 'All' 'Inform' 'Gold' 'Silver' 'Bronze' as card_type_name silent %}
      {% if card_type == ct %}
        <dd class="active">
          {% else %}
        <dd>
      {% endif %}
      <a href="{% url url_string object.slug ct role_line|default:'all' sort_by|default:'ovr' %}">
        {{ card_type_name }}
      </a>
    </dd>
    {% endfor %}
  {% endwith %}
</dl>

<dl class="sub-nav">
  <dt>Role Line:</dt>
  {% with 'all att mid def gk' as role_lines  %}
    {% for rl in role_lines.split %}
      {% cycle 'All' 'Attackers' 'Midfielders' 'Defenders' 'Goalkeepers' as role_lines_name silent %}
      {% if role_line == rl %}
        <dd class="active">
          {% else %}
        <dd>
      {% endif %}
      <a href="{% url url_string object.slug card_type|default:'all' rl sort_by|default:'ovr' %}">
        {{ role_lines_name }}
      </a>
    </dd>
    {% endfor %}
  {% endwith %}
</dl>

<dl class="sub-nav">
  <dt>Sort By:</dt>
  {% with 'ovr att1 att2 att3 att4 att5 att6' as sorts  %}
    {% for sort in sorts.split %}
      {% ifequal role_line 'gk' %}
        {% cycle 'Overall' 'Diving' 'Handling' 'Kicking' 'Reflexes' 'Speed' 'Positioning' as sorts_name silent %}
      {% else %}
        {% cycle 'Overall' 'Pace' 'Shooting' 'Passing' 'Dribbling' 'Defending' 'Heading' as sorts_name silent %}
      {% endifequal %}
      {% if sort_by == sort %}
        <dd class="active">
          {% else %}
        <dd>
      {% endif %}
      <a href="{% url url_string object.slug card_type|default:'all' role_line|default:'all' sort %}">
        {{ sorts_name }}
      </a>
    </dd>
    {% endfor %}
  {% endwith %}
</dl>
{% endwith %}

2 个答案:

答案 0 :(得分:5)

当我学习here时,视图已经传递给上下文(对于基于类的视图)。因此,您可以在模板中执行以下操作,而无需从视图中显式传递kwargs:

 {{ view.kwargs.card_type }}
 {{ view.kwargs.role_line }}
 {{ view.kwargs.sort_by }}

答案 1 :(得分:2)

您可以使用dict.update()

  

update([other])

     

使用其他键中的键/值对更新字典,覆盖现有键。

context.update(self.kwargs)