Jeffrey Hearn and Joss Ingram have published examples of using Wagtail’s hooks system to register custom hallo.js plugins for additional WYSIWYG features.  Using their examples I was able to quickly wire up some plugins that I needed for a Wagtail project, including:

  • Indent and outdent buttons, for nested lists and indented text blocks
  • Superscript and subscript buttons
  • Underline and strikethrough buttons
  • “Paste as plain text” and “edit raw html” buttons (but more on these in another post) 

There was one missing piece that was bugging me though — how to make the buttons stateful, so that (e.g.) when the cursor is within a block of text that’s already superscript, the “superscript” button would show up as already on, and clicking it would disable superscript.

Digging into Wagtail and hallo.js source I found an answer — the `queryState` option to the `hallobutton` constructor.  This option should be sent in as a callback function which can tell the hallo button whether it should be drawn as enabled or disabled: 

[…]

populateToolbar: function(toolbar) {
 var button, widget;

  var getEnclosing = function(tag) {
                    var node = widget.options.editable.getSelection().commonAncestorContainer;
                    return $(node).parents(tag).get(0);
  };



  button = $(’<span></span>‘);
  button.hallobutton({
                    uuid: this.options.uuid,
                    editable: this.options.editable,
                    label: ‘Strikethrough’,
                    icon: ‘fa fa-strikethrough’,
                    command: null,
                    queryState: function(event) {
                        return button.hallobutton(’checked’, !!getEnclosing(”strike”));
                    }
  }); 

  toolbar.append(button);

  button.on(’click’, function(event) {
                    return widget.options.editable.execute(’strikeThrough’);
  });

}

[…] 

This handles the UI aspects of statefulness.  

In some cases — like strikethrough and underline — nothing else is needed: the browser’s `execCommand(”strikeThrough”)` will already check whether the selection is already enclosed in a strike tag, and disable strikethrough if so.

In other cases — like superscript and subscript — the browser’s execCommand function doesn’t seem to implement the toggle behavior; in those cases, the plugin button’s onclick function will need to check for an enclosing sup/sub tag and do the work of removing the formatting instead:

  button.on('click', function(event) {
      return widget.options.editable.execute(
        getEnclosing("sup") ? 'removeFormat' : 'superscript');
  }); 
Filed August 9th, 2014 under wagtail

Wagtail has a built in “Redirects” system that lets you set up redirects for particular URLs.  These are managed independently of your site’s Page tree, which has a few disadvantages:

  • The editor’s user interface just provides a raw URL field for the source of the redirect, instead of letting you add redirects from within the Explorer and see them in their urlspace context.
  • If you set up a redirect at /my-page/redirect-url/ then the “my-page” parent won’t have any knowledge of the redirect that’s underneath it.  This means you’d need to do extra work and database queries any time you want to do something with those redirects in the page hierarchy, like displaying them in their parent page’s navigation menus.
  • You lose all the other built in features of pages, like search integration, workflow, versioning, etc.

So, for typical usage (e.g. avoiding link breakage when pages move around) the built in system is appropriate, but sometimes you may need to treat redirects a bit more like fully managed content.

Luckily it’s easy to set up a custom Page type which acts as a redirect.  You just need to override the “serve” method from the core Page class, for example:

class PageAlias(Page):

    alias_for_page = models.ForeignKey(’wagtailcore.Page’, related_name=’aliases’)

    def serve(self, request):
        return redirect(self.alias_for_page.url, permanent=False)

Now you have a new Page type which editors can add anywhere in their site tree, using the standard user experience including the page chooser interface, which will redirect to your chosen page instead of rendering a template.

Filed May 10th, 2014 under wagtail

Each wagtail Page class has a “template” attribute which tells the system what template (as a string identifier) should be loaded when rendering instances of that Page.  As Serafeim Papastefanos writes in his Wagtail tutorial:

A normal Django template can be used to display each page type. Wagtail either generates automatically (by seperating underscors with capital letters in camelcase for instance BlogIndexPage -> blog_index_page) or you can use the template class attribute. Let’s add a templates foler within the tutorial foler and add another folder named tutorial inside templates and ten add a file named blog_index_page.html to templates with the following content (you must have the following hierarchy wagtailtutorial/tutorial/templates/tutorial/blog_index_page.html):

This lets you specify a custom template per page type.  But what if you want to allow administrators to choose from a set of templates for each page?

The Page.template attribute is only accessed when rendering a page instance, so it’s possible to set up a dynamic template per page instance using a property, for example:

class CustomPage(Page):

    template_string = models.CharField(max_length=255, choices=(
                                         (”myapp/default.html”, “Default Template”), 
                                         (”myapp/three_column.html”, “Three Column Template”,
                                         (”myapp/minimal.html”, “Minimal Template”)))
    @property
    def template(self):
        return self.template_string 

Now your editors can dynamically set the chosen template for each page instance.

Of course in this example, you could also just define a “template” CharField directly in the model, instead of using a property.  But using a property allows you to do even more dynamic things like referencing a foreign key to a database-backed template class that admins can edit through the web, or inspecting the page object’s attributes and returning a different template based on which ones are filled in, etc.

Interactions with Abstract Models 

One caveat, though.   Wagtail uses some metaclass magic to add the default “{{ app-name }}/{{ page-type }}.html” template attribute to each class on initialization, by inspecting the existing class attributes and only adding the default value if the class itself doesn’t provide a “template” attribute:

class PageBase(models.base.ModelBase):
    “”"Metaclass for Page”"”
    def __init__(cls, name, bases, dct):
        super(PageBase, cls).__init__(name, bases, dct)
        […]
        if ‘template’ not in dct:
            # Define a default template path derived from the app name and model name
            cls.template = “%s/%s.html” % (cls._meta.app_label, camelcase_to_underscore(name))

(That’s in wagtail/wagtailcore/models.py)

If you’re using a class inheritance hierarchy for multiple page types which all share a common abstract base — a pattern that’s encouraged in the wagtaildemo source — then you’ll need to make sure you define your custom “template” property on each concrete subclass, rather than on the abstract base class.  It seems that when you define it on the base class, the “template” doesn’t appear in the dct received by that PageBase.__init__ metaclass method, so wagtail will end up overriding your customization.

In case that’s not clear — don’t do this, it won’t work:

class BasePage(Page):
    template_string = models.CharField(max_length=255)

    class Meta:
      abstract = True

    @property
    def template(self):
        return self.template_string

class BlogPage(BasePage):

    author = models.CharField(max_length=255)



class EventPage(BasePage):
    date = models.DateField()
    location = models.CharField(max_length=255)

Instead you’ll need to do something like this, violating DRY:

class BasePage(Page):
    template_string = models.CharField(max_length=255)

    class Meta:
      abstract = True

class BlogPage(BasePage):

    author = models.CharField(max_length=255)

    @property
    def template(self):
        return self.template_string

class EventPage(BasePage):
    date = models.DateField()
    location = models.CharField(max_length=255)

    @property
    def template(self):
        return self.template_string  

There’s probably a way around this with even more metaclass magic, but this is good enough for me.

Filed May 10th, 2014 under wagtail

By default wagtail displays its add/edit view for all pages with two tabs — “Content” and “Promote” — whose contents you define for each page type by setting the .content_panels and .promote_panels like so:

 HomePage.content_panels = [
    FieldPanel('title', classname="full title"),
    FieldPanel('body', classname="full"),
    InlinePanel(HomePage, 'carousel_items', label="Carousel items"),
    InlinePanel(HomePage, 'related_links', label="Related links"),
]

HomePage.promote_panels = [
    MultiFieldPanel(Page.promote_panels, "Common page configuration"),
]

You can also customize the set of panels themselves.  For example, a particular page type might not need to have a “Promote” tab, or you might want a separate “Sidebar” tab to better organize the editor experience.

Here’s how to do that; suppose you have a custom page class called CustomPage:

from wagtail.wagtailadmin.views.pages import (PAGE_EDIT_HANDLERS,
                                              TabbedInterface,
                                              ObjectList)

PAGE_EDIT_HANDLERS[CustomPage] = TabbedInterface([
        ObjectList(CustomPage.general_panels, heading="General"),
        ObjectList(CustomPage.content_panels, heading="Content"),
	ObjectList(CustomPage.sidebar_panels, heading="Sidebar"),
	])

Note that if you do this, your CustomPage class should define the above attributes (in this example, general_panels, content_panels and sidebar_panels) instead of the typical content_panels and promote_panels. 

I’ve filed a pull request with a cleaner API for the sake of argument, though I guess I’m just curious whether this feature can be relied on moving forward.

Filed May 10th, 2014 under wagtail
  • You can limit a PageChooserPanel to a particular type of page:
       PageChooserPanel(‘project’, page_type=‘myapp.SpecialPurposePage’)

 …ok well just one note for now.

Filed May 9th, 2014 under wagtail