sw12k
sw12k

Reputation: 31

In WagTail, how do you display a full document url for document links embedded in richtext?

I'm setting up a wagtail site which needs to display all links as full urls since the pages will also be used as email templates.

Wagtail version 2.5.1

My main issue is document links which are embedded in RichTextFields. The current work around is to have them inserted as external links after they upload the documents.

I've looked at features.register_link_handler but am unclear on how to deal with Document links. I'm assuming that it will need to be in wagtail_hooks.py register_rich_text_features somehow.

Upvotes: 1

Views: 641

Answers (3)

sw12k
sw12k

Reputation: 31

The real answer is to Upgrade to Wagtail 2.7 and then set

WAGTAILDOCS_SERVE_METHOD = "direct" in the settings.

This will provide the direct document when using remote storage.

Upvotes: 1

Martin Zugnoni
Martin Zugnoni

Reputation: 1439

@sw12k I tried to apply your same solution and I couldn't make it work, but... I think I found a much simpler solution that actually made the trick.

In the html template, when you render your RichTextField I moved from:

{{ page.description|safe }}

to this:

{{ page.description|richtext }}

And now document links are well formatted and download links work fine.

Hope it helps.

Upvotes: 0

sw12k
sw12k

Reputation: 31

I ended up creating a register_rich_text_features link handler for this in wagtail_hooks.py

class DocumentFullLinkHandler(DocumentLinkHandler):

@classmethod
def expand_db_attributes(cls, attrs):
    try:
        document = cls.get_instance(attrs)
        current_site = Site.objects.get_current()

        document_url = (
            document.url 
            if document.url.startswith(settings.PATH_PREFIX)
            else f"{settings.PATH_PREFIX}{document.url}"
        )
        full_url = f"https://{current_site.domain}{document_url}"
        return f'<a href="{escape(full_url)}">'
    except (ObjectDoesNotExist, KeyError):
        return "<a>" 

Upvotes: 1

Related Questions