0

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?

Aquiles Carattino
  • 910
  • 1
  • 10
  • 23

1 Answers1

3

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.

LB Ben Johnston
  • 4,751
  • 13
  • 29
  • Thanks, it is what I did, just wanted to know if there was a shorter way that prevented me from updating all the templates where I use those blocks. Perhaps I was missing something obvious somewhere, but it seems I wasn't. – Aquiles Carattino May 08 '20 at 14:10
  • 1
    Hi @AquilesCarattino - I had another dig through the way `StreamField` & `Block` are built and cannot see any other way to read the page (or modal) that the stream field/blocks are part of. You can dig into the source here; https://github.com/wagtail/wagtail/blob/master/wagtail/core/blocks/base.py https://github.com/wagtail/wagtail/blob/master/wagtail/core/fields.py – LB Ben Johnston May 09 '20 at 00:29