1

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?

GEV
  • 397
  • 2
  • 9

2 Answers2

2

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'})
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • Thanks but 1) I wonder if you can achieve that with templates only 2) It doesn't solve my need for a default value in base and override value (although I can probably fix that with an if...else – GEV May 13 '21 at 05:40
  • @GEV: you can work with the **`|default`** template tag: https://docs.djangoproject.com/en/dev/ref/templates/builtins/#default – Willem Van Onsem May 13 '21 at 05:42
  • @GEV: as for adding it to the template, that i currently impossible since it first renders the "parent template", and then only replaces some blocks. – Willem Van Onsem May 13 '21 at 05:44
0

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 %}
GEV
  • 397
  • 2
  • 9