Reputation: 46
I have a site that has custom JS for handling link clicks, so that only part of the page reloads and audio playback isn't interrupted. This requires each link to have an onclick attribute. All of the hard coded links in the site have this, but links in page content created in the wagtail CMS don't. I know there's a couple different ways to achieve this, but I felt like the most elegant would be with wagtail's rewrite handlers.
I followed the steps and added a hook to register my rewrite handler, but it seems that since links with the identifier "page"
are already handled by PageLinkHandler
, this is ignored. I can't find a hook provided by wagtail to override this handler, so I've ended up monkeypatching in the functionality:
from wagtail.models import Page
from wagtail.rich_text.pages import PageLinkHandler
from django.utils.html import escape
@classmethod
def custom_expand_db_attributes(cls, attrs):
try:
page = cls.get_instance(attrs)
return '<a onclick="navigate(event, \'{s}\')" href="{s}">'.format(s=escape(page.localized.specific.url))
except Page.DoesNotExist:
return "<a>"
PageLinkHandler.expand_db_attributes = custom_expand_db_attributes
This code is just placed in the views.py of my frontend. It works, but I want to know if there's an officially supported way to do this without monkeypatching
Upvotes: 0
Views: 94
Reputation: 1296
I think since you want to replace rather than extend some functionality, monkey patching is the correct approach.
Upvotes: 0