在 Wagtail 的一个块中获取页面 url

Getting the page url within a block in Wagtail

我正在尝试使用 Wagtail 2.9 创建一个允许将其文本内容共享到 Twitter 的块。该块本身很简单:

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

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

但是,我想访问该块所在页面的 URL,以便将其作为 link 包含在要共享的消息中。在 quotable_share.html 模板中,我尝试过:

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

但是 none 让我可以访问页面 URL。

有没有一种方法可以访问 URL 而无需在遍历 StreamField 块时将其作为模板变量传递?

来自模板渲染文档 - 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.

因此您需要更新页面模板中的块呈现以使用不同的语法。 {% include_block my_block %}.

您可以对整个流字段或您知道需要可用请求对象的特定块执行此操作。