我是Wagtail的新手,但是我已经完成作业并阅读了文档,并在网上搜索了其他参考文献,但无法弄清楚为什么我无法成功遍历并渲染输入到Steamfield内部各种块中的值。我已经在主页模板中以及该块的模板中进行了尝试。
这是我的模型(议程注释模板现在已注释掉):
class AgendaPage(Page):
author= models.CharField(max_length=255)
date = models.DateField('Post date')
agenda = StreamField([
('agenda_item', blocks.StreamBlock([
('item_title', blocks.TextBlock()),
('item_content', blocks.ListBlock(blocks.StructBlock([
('item_text', blocks.TextBlock()),
('mtg_doc', blocks.StructBlock([
('doc_description', blocks.TextBlock()),
('doc_link', blocks.TextBlock())
]))
])))
]
#,
#template='blocks/agenda_temp.html',
))
])
content_panels = Page.content_panels + [
FieldPanel('author'),
FieldPanel('date'),
StreamFieldPanel('agenda'),
]
当我拥有最基本的模板时,将呈现在编辑器中发布页面时输入的所有值,但其名称位于其前面。因此,在此基本模板中:
{% for block in self.agenda %}
{{ block.value }}
{% endfor %}
如果我尝试分别访问其中的值,那么我什么也没得到。以下仅是示例,但我尝试了许多其他语法组合,包括对名为“ agenda_item”的块使用单独的模板无济于事:
{% if block.block_type == 'item_title' %}
<h2>{{ block.value }}<h2>
{% endif %}
即使我的Streamfield嵌套确实保存到数据库并使用简单的{{block}}标签呈现,也可能有问题吗?
更新:我接受了这个答案,因为它解决了我的模板渲染问题,但是也许此屏幕快照将有助于说明我现有的问题。通过单击编辑器界面中的+,可以使用streamblock'agenda_item'将其他子块添加到'agenda_item'以及添加一个新的'agenda_item',这非常好,几乎完全满足我的需要。问题是我只希望为新的“ agenda_item”提供“ item_title”,而不为“ agenda_item”中的孩子提供。这就是为什么我本来就这样嵌套流域子级,但是后来却无法访问模板渲染中最低级别的嵌套块的原因。因此,缩减流域的级别可以解决此问题,但现在用户可能会在不必要或无效的地方错误地添加了item_title。我的问题是:
我现有的模型和面板定义如下所示:
agenda = StreamField([
('agenda_item', blocks.StreamBlock([
('item_title', blocks.TextBlock()),
('item_text', blocks.TextBlock()),
('mtg_doc', blocks.StructBlock([
('mtg_doc_upload', DocumentChooserBlock(required=True)),
('submitted_late', blocks.BooleanBlock(required=False, help_text='Submitted Late')),
('heldover', blocks.BooleanBlock(required=False, help_text='Held Over')),
('heldover_from', blocks.DateBlock(required=False, help_text="Held Over From")),
])),
('item_audio', DocumentChooserBlock(required=False)),
]))
])
content_panels = Page.content_panels + [
FieldPanel('author'),
FieldPanel('date'),
FieldPanel('mtg_date'),
FieldPanel('mtg_time'),
StreamFieldPanel('mtg_media'),
StreamFieldPanel('agenda'),
]
按照当前编写代码的方式,顶级块始终为type agenda_item
,因此在遍历它们时需要考虑到这一点:
{% for block in self.agenda %}
{% if block.block_type == 'agenda_item' %} {# will always be true, but included here for clarity #}
{% for subblock in block.value %}
{% if subblock.block_type == 'item_title' %}
<h2>{{ subblock.value }}</h2>
{% elif subblock.block_type == 'item_content' %}
rendering for item_content...
{% endif %}
{% endfor %}
{% endif %}
{% endfor %}
但是,我认为您根本不需要真正的agenda_item
StreamBlock-它只是添加了不必要的间接级别,这使您不胜其烦。据我所知,您可以通过在顶层创建item_title
和item_content
两种可用的块类型来获得相同的结果:
agenda = StreamField([
('item_title', blocks.TextBlock()),
('item_content', blocks.ListBlock(blocks.StructBlock([
('item_text', blocks.TextBlock()),
('mtg_doc', blocks.StructBlock([
('doc_description', blocks.TextBlock()),
('doc_link', blocks.TextBlock())
]))
])))
])
(或者您是否打算agenda_item
成为StructBlock ...?)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句