GEV
GEV

Reputation: 467

Django How can I repeat a block within a template

My Django base template looks like this:

#base.html

<title>{% block title %} My Default Title {% endblock title %}</title>
<meta property="og:title" content="{% block og_title %} My Default Title {% endblock og_title %}">

Then if I'd like to override the default title for specific page:

#page.html
{% extends "base.html" %}
{% block title %} My page  Title {% endblock title %}
{% block og_title %} My page Title {% endblock _ogtitle %}

How can I set the base.html block title once (like a variable) and use across my document? Then, if I need, I override the title once in the page.html and it gets populated across?

Upvotes: 1

Views: 456

Answers (2)

GEV
GEV

Reputation: 467

Answering my own question:

There is no good way to do that. There are a few workarounds mentioned here: How to repeat a "block" in a django template

(I saw this question in advance. But wasn't sure if anything changed)

This is the workaround I chose:

#base.html

<title>{% block title %} My Default Title {% endblock title %}</title>
<meta property="og:title" content="{% block og_title %} My Default Title {% endblock og_title %}">
#page.html
{% extends "base.html" %}
{% block title %} {% block og_title %} My page  Title {% endblock og_title %}{% endblock title %}

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476574

You can work with a variable in the base template:

<title>{{ my_title|default:"my page title" }}</title>
<meta property="og:title" content="{{ my_title|default:"my page title" }}">

In your view, you then pass a value for my_title:

from django.shortcuts import render

def some_view(request):
    # …
    return render(request, 'some_template.html', {'my_title': 'some_title'})

Upvotes: 3

Related Questions