Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Django Basics Django Templates Templates

Are dynamic titles possible in Django like in Jekyll (YAML front matter)?

In Jekyll, there's something called 'front matter' that allows you to define the title for each page individually; it is enclosed in 3 dashes on either side:


title: TeamTreeHouse

Instead of declaring a title for each page in my Django templates title tags, how can I set it so it's automatically based off what the name of the webpage is?

This: {% block title %}{{ page.title }}{% endblock %}

Instead of: {% block title %}My Blog{% endblock %}

I figured, in theory, if I declare a 'Page' object in my models, I can add a title attribute and it would work, but is this the right way to go about it?

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,454 Points

You are on the right track. By placing default text in the base layout.html that all your pages extend from:

{% block title %}My Site{% endblock %}

Then adding an customization to each template that extends layout.html:

{% block title %}{{ title_text }}{% endblock %}

You can then assign title_text in the page context created in the view. You are free to create the title_text variable any way you like: adding it to the page as an attribute, or as it's own context variable, etc. the template variable can be called anything you wish. title_text is just an example.

Post back if you need more info.