Yasel
Yasel

Reputation: 3120

How to access page title in Django templates?

How can I get the page title in the template? I know there are ways to do this with javascript, but I'll prefer a template-tag or a variable if it exists.

Upvotes: 2

Views: 3786

Answers (1)

The page title is an html element (<title>Title Here</title>), and django has no idea what that is.

Django's templates render the raw HTML text, which a browser parses and only then does the concept of a page title exist for javascript to parse.

If you need it in django, you'd want to ensure django is building that title tag and you would access it in the same way you'd display any other variable in a template.

It's probably best left to the DOM tools since a title might be created in any number of ways. If you absolutely need it in django, I would probably parse the final rendered HTML with an HTML parser like BeautifulSoup.

title = BeautifulSoup(mytemplate.render(Context({}))).html.head.title

Upvotes: 6

Related Questions