0

我正在尝试创建一个索引页面,其中包含指向 Wagtail 中多个照片库的链接。GalleryIndexPage 模型如下所示:

class GalleryIndexPage(Page):
  subpage_types = ['home.GalleryPage']

  gallery_thumb = StreamField ([
      ('cover_photo', ImageChooserBlock()),
      ('title', blocks.CharBlock()),
      ('link', URLBlock()),
  ])

  content_panels = Page.content_panels + [
      StreamFieldPanel('gallery_thumb'),
  ]

我很难用围绕每组数据的“画廊项目”类将它渲染到模板中。我意识到它当前正在循环并为 Streamfield 内的每个块添加一个“画廊项目”类,而不是围绕整个 Streamfield 集。这是我的模板代码:

<div class="photo-gallery">
{% for block in self.gallery_thumb %}
<div class="gallery-item">
  {% if block.block_type == 'cover_photo' %}
  <div class="thumb">
    {% image block.value fill-200x150 %}
  </div>
  {% endif %}
  {% if block.block_type == 'title' %}
  <div class="title">
    <p>{{ block.value }}</p>
  </div>
  {% endif %}
  {% if block.block_type == 'link' %}
  <div class="link">
    <a href="{{ block.value }}">View Gallery</a>
  </div>
  {% endif %}
</div>
{% endfor %}

我还有其他方法可以解决这个问题吗?

编辑:我在我的 StreamField 中添加了一个 StructBlock ,如下所示:

class GalleryIndexPage(Page):
  subpage_types = ['home.GalleryPage']

  gallery = StreamField ([
      ('gallery_item', blocks.StructBlock([
          ('cover_photo', ImageChooserBlock()),
          ('title', blocks.CharBlock()),
          ('link', URLBlock()),
      ], icon='user'))
  ])

  content_panels = Page.content_panels + [
      StreamFieldPanel('gallery'),
  ]

我不确定如何在我的模板中访问这些值?这是我到目前为止所拥有的:

  <div class="photo-gallery">
    {% for block in self.gallery %}
    <div class="gallery-item">
      <div class="thumb">
        {% image self.cover_photo width-200 %}
      </div>
      <div class="title">
        <p>{{ self.title }}</p>
      </div>
      <div class="link">
        <a href="{{ self.link }}">>> View Gallery</a>
      </div>
    </div>
    {% endfor %}
  </div> 
4

2 回答 2

3

看起来你想要的是一个由图像、标题和链接组成的单个 gallery_item 块。您可以通过使用更简单的块类型创建自己的块类型来做到这一点。请参阅http://docs.wagtail.io/en/v1.5.3/topics/streamfield.html#structural-block-types

你可以这样做:

('gallery_item', blocks.StructBlock([
    ('title', blocks.CharBlock()),
    ('link', blocks.URLBlock()),
    ('image', ImageChooserBlock()),
], icon='xyz'))

您也可以将其创建为 Python 类,这是我通常喜欢做的,这在我上面链接到的部分的最后一部分中进行了介绍。

您可以为此块创建自己的模板。

在模板中,每个块都有两个属性,value并且block_type. 因此,您将访问例如titlewith {{ self.title.value }}

请参阅http://docs.wagtail.io/en/v1.5.3/topics/streamfield.html#template-rendering

于 2016-08-05T20:47:58.700 回答
2

我可以使用以下代码访问模板中 StructBlock 的值:

<div class="photo-gallery">
{% for block in self.gallery %}
<div class="gallery-item">
  <div class="thumb">
    {% image block.value.cover_photo fill-200x150 %}
  </div>
  <div class="title">
    <p>{{ block.value.title }}</p>
  </div>
  <div class="link">
    <a href="{{ block.value.link }}">>>View Gallery</a>
  </div>
</div>
{% endfor %}

非常感谢您的帮助!

于 2016-08-08T15:53:24.560 回答