How to detect type of page in template syntax?

1,503 views
Skip to first unread message

Anthony Plescia

unread,
Jun 30, 2015, 4:12:29 PM6/30/15
to wag...@googlegroups.com
Hello!

Is there a way to check the type of a page in the template file for it?

Basically, I'm trying to populate a navigation bar with certain items depending on what page you're on. 

For example, say I'm on a CatPage, and there are two subpages: GarfieldPage and TabbyPage. Is there a way to 'detect' what page I'm on in an if statement, for example? (i.e {% if self.type != CatPage %} ... {% elif self.type == GarfieldPage %} ... {% endif %} or something similar). I tried finding a method that could do this in the wagtail repository, but I came up short. Any help would be great.

Thanks!

Anthony

Nigel Fletton

unread,
Jun 30, 2015, 6:32:02 PM6/30/15
to wag...@googlegroups.com
Hi Anthony

There's a get_verbose_name() method on the Page model that you could use if you're happy to work with the model's verbose name or, the better approach is to create a filter as per this SO answer: http://goo.gl/D1tHBX

cheers
Nigel

Matthew Westcott

unread,
Jun 30, 2015, 7:32:16 PM6/30/15
to wag...@googlegroups.com
Nigel has given a good direct answer, so I'll give the slightly more philosophical one :-)

Wagtail doesn't provide a way to access the current page type within a template, and - as far as I'm aware - neither does Django. Whenever you find a seemingly simple feature that's missing from Django, it often means that the Django developers made a deliberate decision not to implement it, to discourage bad practices.

I don't know what the story is here, but my guess is that they were trying to steer people away from explicit type checking, and use the preferred Python approach of "duck typing" instead <http://stackoverflow.com/a/154156/1853523>. This is based on the idea that you're only really interested in the behaviour of the object, not its type - "it doesn't matter if it's a duck, as long as it quacks like a duck..."

So, following that principle here - it means that instead of switching behaviour in the template according to the page type, it's better to implement the desired behaviour as part of the class itself. For example, to provide different navigation bars, you might implement separate 'get_menu_items' methods for each class:

class GarfieldPage(CatPage):
....
def get_menu_items(self):
return ['news', 'lasagna']

class TabbyPage(CatPage):
....
def get_menu_items(self):
return ['news', 'milk']

You would then access 'self.get_menu_items' within your template.

Cheers,
- Matt
Reply all
Reply to author
Forward
0 new messages