wagtailwagtail-streamfieldwagtail-pageurl

Getting the page url within a block in Wagtail


Using Wagtail 2.9, I am trying to create a block that allows to share its text content to Twitter. The block itself is straightforward:

class QuotableShare(StructBlock):
    text = TextBlock(required=True)

    class Meta:
        icon = 'fa-twitter'
        template = 'blocks/quotable_share.html'

However, I would like to have access to the URL of the page where the block appears, to include it as a link in the message to be shared. Within the quotable_share.html template, I've tried:

{{ request.get_full_path }}
{{ request.path }}
{{ request.full_path }}

But none gave me access to the page URL.

Is there a way of accessing the URL without passing it as a template variable while iterating through the StreamField blocks?


Solution

  • From the docs on template rendering - https://docs.wagtail.io/en/latest/topics/streamfield.html#template-rendering

    Writing {{ my_block }} is roughly equivalent to {% include_block my_block %}, but the short form is more restrictive, as it does not pass variables from the calling template such as request or page; for this reason, it is recommended that you only use it for simple values that do not render HTML of their own.

    So you will need to update your block rendering in your page template to use the different syntax. {% include_block my_block %}.

    You can either do this for the entire stream field or for specific blocks that you know need the request object available.