Evgenii Legotckoi
Jan. 6, 2019, 6:48 p.m.

Django - Tutorial 043. template tags to form breadcrumb with shema.org support

I share my implementation of built-in tags to form breadcrumbs with support for schema.org markup, as well as support for bootstrap css.

Wrote these tags to speed up site development speed. Now the work moves much faster, because the code has become more compact, and correcting errors in the breadcrumbs markup has become much easier, since now you only need to correct the code in one place.


Suppose you have a core application that is responsible for some common functionality and it has a directory template_tags with the file core.py for the formation of all embedded tags. Add 3 inclusion tags and one simple tag to form 4 breadcrumb components.

  • breadcrumb_schema - to keep current schema from schema.org markup
  • breadcrumb_home - to form the root of the site
  • breadcrumb_item - to form elements of the site structure tree
  • breadcrumb_active - to form an element of the current page of the site

core.py

Look at the contents of the python file with these tags.

  1. # -*- coding: utf-8 -*-
  2.  
  3. from django import template
  4.  
  5. register = template.Library()
  6.  
  7.  
  8. @register.simple_tag
  9. def breadcrumb_schema():
  10. return "http://schema.org/BreadcrumbList"
  11.  
  12.  
  13. @register.inclusion_tag('core/breadcrumb_home.html')
  14. def breadcrumb_home(url='/', title=''):
  15. return {
  16. 'url': url,
  17. 'title': title
  18. }
  19.  
  20.  
  21. @register.inclusion_tag('core/breadcrumb_item.html')
  22. def breadcrumb_item(url, title, position):
  23. return {
  24. 'url': url,
  25. 'title': title,
  26. 'position': position
  27. }
  28.  
  29.  
  30. @register.inclusion_tag('core/breadcrumb_active.html')
  31. def breadcrumb_active(url, title, position):
  32. return {
  33. 'url': url,
  34. 'title': title,
  35. 'position': position
  36. }

If everything is clear with the breadcrumb_schema () tag, it simply returns the definition of the markup scheme, then there are more questions with other tags.

All markup is formed from three main parameters:

  • url - link to the item page
  • title - page title
  • position - all elements in the markup should be numbered. For example, 0, 1, 2, 3, etc.

For breadcrumb_home() I do not add any position because there is no point in it, there will always be position 0. Besides, in my case there is an icon instead of a title, so the template will have a different one.

In the case of the other two tags, we will need to specify the position.

Шаблоны

Immediately make a reservation about the home icon. I use the Material Design Icons package, so there will be a span tag with classes mdi mdi-home .

breadcrumb_home.html

  1. <li class="breadcrumb-item" itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem">
  2. <a itemprop="item" href="{{ url }}">
  3. <span class="mdi mdi-home">
  4. <span class="d-none" itemprop="name">{{ title }}</span>
  5. </span>
  6. </a>
  7. <meta itemprop="position" content="1" />
  8. </li>

breadcrumb_item.html

  1. <li class="breadcrumb-item" itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem">
  2. <a itemprop="item" href="{{ url }}">
  3. <span itemprop="name">{{ title }}</span>
  4. </a>
  5. <meta itemprop="position" content="{{ position }}" />
  6. </li>

breadcrumb_active.html

  1. <li class="breadcrumb-item active" itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem">
  2. <link itemprop="item" href="{{ url }}">
  3. <span itemprop="name">{{ title }}</span>
  4. <meta itemprop="position" content="{{ position }}" />
  5. </li>

Applying tags in a template

Ну и приведу кусок кода из шаблона статьи, где это применяется в боевых условиях.

  1. {% extends 'home/base.html' %}
  2. {% load core %}
  3. <ul class="breadcrumb bg-light" itemscope itemtype="{% breadcrumb_schema %}">
  4. {% url 'home:index' as home_index_url %}
  5. {% breadcrumb_home home_index_url 'EVILEG' %}
  6. {% url 'knowledge:index' as knowledge_index_url %}
  7. {% breadcrumb_item knowledge_index_url _('Articles') 2 %}
  8. {% breadcrumb_item article.section.get_absolute_url article.section.title 3 %}
  9. {% breadcrumb_active article.get_absolute_url article.title 4 %}
  10. </ul>

Conclusion

Now imagine that instead of these 9 lines in the article template, you would have to write each component for proper markup. The number of lines the code would increase threefold, and with the increase of this monotonous functionality, it becomes more difficult to maintain the code of the site and quickly fix it.

Recommended articles on this topic

By article asked0question(s)

1

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html