How to add Wagtail ‘admin’ menu to custom templates?
On templates that derive from the Wagtail Page model, there is a small Wagtail icon/menu in the lower right corner. This provides a quick way to edit the page and/or jump to the Wagtail Admin. However, this menu does not appear on custom view templates that are not derived from Wagtail Page model.
How can I tell Wagtail to display the small menu on my frontend templates, so the pages have consistent navigation?
Answer
The standard Wagtail user bar is rendered by placing in your template:
{% load wagtailuserbar %}
{% wagtailuserbar 'top-left' %}
I typically just put the above in base.html
. The 'top-left'
designation, of course, tells the template tag where to render the user bar. Reference
However, the wagtailuserbar is only rendered for Wagtail pages. What you want to do is render the user bar with only the Go to Wagtail Admin option (because no other options would be relevant). Therefore, you could create your own template tag and place it in base.html
beside the wagtailuserbar
. You would set it up so that it renders if there IS NO page
in the context (the wagtailuserbar
template tag checks to make sure there IS a page
in the context). To create your tag, just start with the code from wagtailuserbar.py
and modify it to create a template tag called wagtailuserbar_admin_only
(untested):
from django import template from django.template.loader import render_to_string from wagtail.admin.templatetags.wagtailuserbar import get_page_instance from wagtail.admin.userbar import (AdminItem) @register.simple_tag(takes_context=True) def wagtailuserbar_admin_only(context, position='bottom-right'): # Find request object try: request = context['request'] except KeyError: return '' # Don't render without a user because we can't check their permissions try: user = request.user except AttributeError: return '' # Don't render if user doesn't have permission to access the admin area if not user.has_perm('wagtailadmin.access_admin'): return '' # Only render if the context does NOT contain a variable referencing a saved page page = get_page_instance(context) if page: return '' # Render the items rendered_items = [AdminItem()] # Render the userbar items return render_to_string('wagtailadmin/userbar/base.html', { 'request': request, 'items': rendered_items, 'position': position, })
Then, to use in templates, place in base.html
:
{% load wagtailuserbar_admin_only %}
{% wagtailuserbar_admin_only 'top-left' %}