Duplicate the content of the block in Django template

Suppose I have the following code in base.html:

<meta name="description" content="{% block description %}Some description{% endblock %}">

Other templates that extend base.html, override the contents of the block and so each page gets its own description.

What if I want to add <meta property="og:description" content="" />, where the value of the content should equal the above value?

How can I add the contents of the block into another place?

Not sure {% block %} is the template feature you need.

I think you can set a variable instead of the block:

<meta name="description" content="{{ description|default:"Some description"}}">
<meta name="og:description" content="{{ description|default:"Some description"}}">

And in each view, you can define extra_context :

class YourView(View):
    extra_context = {"description": "Your description"}

An idea could be to use django-template-macros. So we can install this with:

pip install django-templates-macros

and add it as one of the installed apps:

# settings.py

# …

INSTALLED_APPS = [
    # …,
    'macros',
    # …
]

# …

and we can then use this in the "root" template as:

{% load macros %}
{% macro description %}
  {% block description %}some description{% endblock %}
{% enddescription %}

<meta name="description" content="{% usemacro description %}">
<meta property="og:description" content="{% usemacro description %}"/>

But this is very likely not a good idea: descriptions need to be HTML encoded, so > should be rewritten to &gt; and & to &amp;. Django's template language automatically does this with variables, not with blocks.

Вернуться на верх