(content_personalization)= # 内容个性化 Wagtail 的内置功能在很多情况下足以满足内容个性化需求。我们可以配置 StreamField 块,让它根据请求上下文只对特定细分群体显示。在编辑器中,预览模式让用户能够在发布前逐段查看。编辑团队因此可以在一个页面内为不同受众细分群体定制内容,并预览该内容在每个细分群体下的呈现。 这支持以下使用场景: - 时间感知的变体:在特定时间段内,或只在一定期限内。 - UTM 广告系列参数或来源站点细分。 - 仅限会员的内容,面向已登录用户或特定用户组中的用户。 如果需要更高级的细分或由分析驱动的定向,可以考虑外部包 [wagtail-personalisation](https://github.com/wagtail/wagtail-personalisation)。想从宏观上了解核心功能与该包在范围上的差异,请参阅我们的[内容个性化说明](https://wagtail.org/content-personalization/)。 ## 分段内容块 这个示例定义一个块,它在存储富文本的同时存储一个细分选项。我们使用自定义的 `form_layout` 和 [`BlockGroup`](wagtail.blocks.BlockGroup),把细分配置收在折叠的“Settings”区域里。[块类](wagtail.blocks.Block)的 `get_context` 方法读取请求,以判断访客属于哪个细分群体。 渲染 StreamField 内容时请务必使用 [`{% include_block %}`](streamfield_template_rendering),这样块才能收到父上下文,包括 `get_context` 所用的 `request` 对象。 ```python class SegmentedContentBlock(StructBlock): content = RichTextBlock() segment = ChoiceBlock( choices=[ ("all", "All visitors"), ("logged_in", "Logged-in users"), ("anonymous", "Anonymous visitors"), ], default="all", ) def get_context(self, value, parent_context=None): context = super().get_context(value, parent_context) request = parent_context.get("request") if parent_context else None preview = getattr(request, "personalization_preview_segment", None) context["is_authenticated"] = ( preview == "logged_in" if preview else (request.user.is_authenticated if request else False) ) return context class Meta: icon = "group" template = "blocks/segmented_content_block.html" preview_value = { "content": "

Welcome back! Exclusive content for members.

", "segment": "logged_in", } description = "Content targeted to specific audience segments" form_layout = BlockGroup( children=["content"], settings=["segment"], ) ``` 这类简单的分段可以很方便地加到任何 StructBlock 中。关于块本身已经比较复杂时如何进行分组和排序的细节,见 [](structblock_custom_order_and_grouping)。 ### 块模板 该模板根据选中的细分选项决定是否渲染内容。这里我们还为每个细分群体分别设置了不同的样式。 ```html+django {% load wagtailcore_tags %} {% if self.segment == "all" %}
{{ self.content|richtext }}
{% elif self.segment == "logged_in" and is_authenticated %}
{{ self.content|richtext }}
{% elif self.segment == "anonymous" and not is_authenticated %}
{{ self.content|richtext }}
{% endif %} ``` ## 在管理后台中预览细分群体 你可以在页面上使用[预览模式](wagtail.models.AbstractPage.preview_modes),让编辑在匿名和已登录变体之间切换。这个 mixin 会把选中的模式存到请求上,让块的 `get_context` 在预览时应用它。 ```python class PersonalizationPreviewMixin: default_preview_mode = "anonymous" preview_modes = [ ("anonymous", _("Anonymous visitor")), ("logged_in", _("Logged-in user")), ] def serve_preview(self, request, mode_name): request.personalization_preview_segment = mode_name return super().serve_preview(request, mode_name) ``` ## 页面级分段 Wagtail 也内置支持页面级的分段,体现在它的两项功能上。 ### 用可路由页面做广告系列分段 [可路由页面](routable_page_mixin)功能可以配置为在不同路由下提供该页面的变体。这对创建广告系列专用的链接特别有用,不必复制页面,也不会让站点内容随着时间不受控地膨胀。 ### 用私有页面做仅限会员的内容 Wagtail 内置支持[私有页面](private_pages),因此你可以创建只有已登录用户或特定用户组中的用户才能访问的页面或整个站点区域。