Evgenii Legotckoi
Evgenii LegotckoiJan. 6, 2019, 7:48 a.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.

# -*- coding: utf-8 -*-

from django import template

register = template.Library()


@register.simple_tag
def breadcrumb_schema():
    return "http://schema.org/BreadcrumbList"


@register.inclusion_tag('core/breadcrumb_home.html')
def breadcrumb_home(url='/', title=''):
    return {
        'url': url,
        'title': title
    }


@register.inclusion_tag('core/breadcrumb_item.html')
def breadcrumb_item(url, title, position):
    return {
        'url': url,
        'title': title,
        'position': position
    }


@register.inclusion_tag('core/breadcrumb_active.html')
def breadcrumb_active(url, title, position):
    return {
        'url': url,
        'title': title,
        'position': position
    }

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

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

breadcrumb_item.html

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

breadcrumb_active.html

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

Applying tags in a template

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

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

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
MB

Qt - Test 001. Signals and slots

  • Result:57points,
  • Rating points-2
MB

C++ - Test 001. The first program and data types

  • Result:60points,
  • Rating points-1
GK

C++ - Test 005. Structures and Classes

  • Result:0points,
  • Rating points-10
Last comments
J
JonnyJoJune 8, 2023, 9:14 a.m.
Qt/C++ - Lesson 019. How to paint triangle in Qt5. Positioning shapes in QGraphicsScene Евгений, здравствуйте! Решил поэкспериментировать немного с кодом из этого урока, нарисовать вместо треугольника квадрат и разобраться с координатами. В итоге, запутался. И ни документация,…
J
JonnyJoMay 25, 2023, 11:24 a.m.
How to make game using Qt - Lesson 2. Animation game hero (2D) Евгений, благодарю!
Evgenii Legotckoi
Evgenii LegotckoiMay 25, 2023, 1:49 a.m.
How to make game using Qt - Lesson 2. Animation game hero (2D) Код на строчка 184-198 вызывает перерисовку области на каждый 4-й такт счётчика. По той логике не нужно перерисовывать объект постоянно, достаточно реже, чем выполняется игровой слот. А слот вып…
J
JonnyJoMay 21, 2023, 7:49 a.m.
How to make game using Qt - Lesson 2. Animation game hero (2D) Евгений, благодарю! Всё равно не совсем понимаю :( Если муха двигает ножками только при нажатии клавиш перемещение, то что, собственно, делает код со строк 184-198 в triangle.cpp? В этих строчка…
Evgenii Legotckoi
Evgenii LegotckoiMay 21, 2023, 2:57 a.m.
How to make game using Qt - Lesson 2. Animation game hero (2D) Добрый день. slotGameTimer срабатывает по таймеру и при каждой сработке countForSteps увеличивается на 1, это не зависит от нажатия клавиш, нажатая клавиша лишь определяет положение ножек, котор…
Now discuss on the forum
T
TwangerJune 7, 2023, 8:12 a.m.
Ошибка при выполнении триггерной функции (GreenPlum) Есть 3 таблицы fact_amount со структурой: CREATE TABLE fact_amount ( id serial4 NOT NULL, fdate date NULL, type_activity_id int4 NULL, status_id int4 NULL, CONSTRAINT fact…
AR
Alexander RyabikovJune 6, 2023, 10:35 a.m.
Работа с QFileSystemModel Вопросик по теме QFileSystemModel в Linux. Он, как и положено, обновляется самостоятельно, если директория локальная. Но, вот, сетевая папка (у меня шара samba) не обновляется. Как её можно…
Evgenii Legotckoi
Evgenii LegotckoiApril 16, 2023, 1:07 a.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Да, это возможно. Но подобные вещи лучше запускать через celery. То есть drf принимает команду, и после этого регистрирует задачу в celery, котроый уже асинхронно всё это выполняет. В противном …
АБ
Алексей БобровDec. 14, 2021, 4:03 p.m.
Sorting the added QML elements in the ListModel I am writing an alarm clock in QML, I am required to sort the alarms in ascending order (depending on the date or time (if there are several alarms on the same day). I've done the sorting …

Follow us in social networks