Inclusion templatetag with counter
<h1>What I want</h1>

<p>Inclusion Templatetag which returns number of uses and don't break when using template inheritance. I tried to storage counter in context, but it does not work as I intended.</p>

<p>base.html</p>

<pre><code>{% block body %}
  {% my_tag %}&lt;br&gt;
  {% my_tag %}&lt;br&gt;
{% endblock %}
</code></pre>

<p>page.html</p>

<pre><code>{% extends 'base.html' %}
{% block body %}
    {{ block super }}
    {% my_tag %}&lt;br&gt;
    {% my_tag %}&lt;br&gt;
{% endblock %}
</code></pre>

<p>rendered result:</p>

<pre><code>1
2
3
4
</code></pre>

<h1>What I tried</h1>

<pre><code>@register.inclusion_tag('tagtemplate.html', takes_context=True)
def my_tag(context):
    counter = context.get('tag_counter', 1)
    ctx = {'tag_counter': counter}
    context['tag_counter'] = counter + 1
    return ctx
</code></pre>

<p>And result:</p>

<pre><code>1
2
1
2
</code></pre>

<h1>And what worked</h1>

<p>Added middleware which added counter to request</p>

<pre><code>class TagCounterMiddleware(object):
    def process_request(self, request):
        request.tag_counter = 1
</code></pre>

<p>and changed template tag</p>

<pre><code>@register.inclusion_tag('tagtemplate.html', takes_context=True)
def my_tag(context):
    request = context.get['request']
    ctx = {'tag_counter': request.tag_counter}
    request.tag_counter += 1
    return ctx
</code></pre>

<p>Thanks to @SardorbekImomaliev for his suggestion! :)</p>

<p>I suggest putting your counter in <code>request</code>. Something like this.</p>

<pre><code># This code wasn't checked
@register.inclusion_tag('tagtemplate.html', takes_context=True)
def my_tag(context):
    counter = getattr(context['request'], 'tag_counter', 0)
    request.tag_counter = counter + 1
    context['request'] = request
    return context 
</code></pre>

python django python-2.7 django-templates django-views