假设我正在遵循 您的第一个 Wagtail 站点教程,但我想使用 Streamfield,而不是单独的 RichTextField 或 BlogPageGalleryImage。例如:
class BlogPage(Page):
date = models.DateField("Post date")
intro = models.CharField(max_length=250)
body = RichTextField(blank=True)
...变成...
class BlogPage(Page):
body = StreamField([
('heading', blocks.CharBlock(classname="full title")),
('intro', blocks.RichTextBlock()),
('body', blocks.RichTextBlock()),
('image', ImageChooserBlock()),
], null=True, blank=True,)
我如何(或者我可以)从 Streamfield 中提取第一个图像和 intro 的开头(...因为我无法限制长度)以在 blog_index_page.html 模板中使用,并避免使用单独的字段和 BlogPageGalleryImage 上课?因此更换此模板:
{% for post in blogpages %}
{% with post=post.specific %}
<h2><a href="{% pageurl post %}">{{ post.title }}</a></h2>
{% with post.main_image as main_image %}
{% if main_image %}{% image main_image fill-160x100 %}{% endif %}
{% endwith %}
<p>{{ post.intro }}<p>
{% endwith %}
{% endfor %}
还有类似这样的东西:
{% for post in blogpages %}
{% with post=post.specific %}
<h2><a href="{% pageurl post %}">{{ post.title }}</a></h2>
{{ post.body.image.first() }}
<p>{{ post.intro.get_words(50) }}</p>
{{ post.body|richtext }}
{% endwith %}
{% endfor %}
非常感谢。
五年后我也遇到了同样的问题,所以希望当有人偶然发现这个问题时它能有所帮助。通过在
BlogIndexPage
类中创建一个方法来解决这个问题,该方法检查主体(StreamField)中是否有图像块并从第一个图像块重新调整第一个图像。
def first_body_image(self):
image_blocks = [block for block in self.body if block.block_type == 'image']
if not image_blocks:
return None
return image_blocks[0].value