Search code examples
pythondjangotemplatespluralize

Django {% blocktrans %}: How to handle pluralization inside a for loop?


I have the following loop in my Django template:

{% for item in state.list %}

    <div> HTML (CUSTOMERS BY STATE) </div>

    <!-- print sum of customers at bottom of list -->
    {% if forloop.last %}
        <h4>{{ forloop.counter }} Valued Customers</h4>
    {% endif %}

{% endfor %}

Obviously, if I end up with only one customer, I'd like to print singular "Valued Customer"

According to Django's docs, one should use blocktrans. Tried the following, a few flavors of nesting:

    {% blocktrans count %}
        {% if forloop.last %}
            <h4>
                {{ forloop.counter }}
                &nbsp;Valued Customer
                {% plural %}
                &nbsp;Valued Customers
            </h4>
        {% endif %}
    {% endblocktrans %} 

Keep getting TemplateSyntaxError: Invalid block tag: 'blocktrans', expected 'empty' or 'endfor'

Is there no way to combine with another loop? Any ideas how to solve? Thanks!


Solution

  • Probably, you forgot to load translation tags. Add following line at the top of your template:

    {% load i18n %}
    

    After you fix that, note that for a blocktrans tag after count a variable, whose value will serve for plural detection, should be specified, so you probably need something like

    {% blocktrans count count=forloop.counter %}