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?
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 >
and &
to &
. Django's template language automatically does this with variables, not with blocks.