gersande
gersande

Reputation: 463

Django - automating certain template behaviours

so essentially I'm a recent convert to Django (and Python for the matter) from PHP. In PHP I'm used to being able to automate many things, especially when writing HTML I used to be able to write such commands such as <?php get_head() ?> and it would go fetch all the meta information that needs to be inside the <head></head> of the HTML page. Is there any such functionality built into Django, or am I going to have to write all the HTML manually?

Thanks so much for any pointers.

Upvotes: 0

Views: 42

Answers (1)

Ziyan
Ziyan

Reputation: 71

You are going to love the extends and block tags.

Assuming you already got a templated page working, you can extract the basic setup of your HTML page like this:

Create a template called base.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>{% block title %}{% endblock %}</title>
    {% block head %}{% endblock %}
  </head>
  <body>
    {% block body %}
      Empty page.
    {% endblock %}
  </body>
</html>

Now, in your page template called page.html, you can extend your base template and override any blocks:

{% extends "base.html" %}
{% block title %}Page 1 title{% endblock %}
{% block body %}
   Real page content.
   {% block main %}
      Subpage of page.html can also override this main block.
   {% endblock %}
{% endblock %}

But Hamish is right, do checkout the doc: https://docs.djangoproject.com/en/dev/topics/templates/

Upvotes: 1

Related Questions