django pluralize Filter

If the value is not 1, '1', or an object of length 1, the pluralize filter outputs an “s” or the value of the suffix argument if one is used.

Variable

classes = {
    'Python': [
        'Intro Python', 'Advanced Python', 'Data Science', 'Django'
    ],
    'Databases': [
        'Intro PostgreSQL', 'Intro MySQL', 'Intro SQL Server', 'Intro Oracle'
    ],
    'Web': [
        'HTML', 'CSS', 'JavaScript'
    ],
    'XML': [
        'Intro XML'
    ]
}

Template

<ol>
  {% for category, titles in classes.items %}
    <li>
      {{ category }}: {{ titles|length }}
      class{{ titles|pluralize:"es" }}
    </li>
  {% endfor %}
</ol>

Result

<ol>
  <li>Python: 4 classes</li>
  <li>Databases: 4 classes</li>
  <li>Web: 3 classes</li>
  <li>XML: 1 class</li>
</ol>

Commentary

Super useful. Much easier and cleaner than using conditional expressions to decide when to pluralize a word.

posted @ 2023-05-30 09:31  Oops!#  阅读(8)  评论(0编辑  收藏  举报