如果 booleanBlock 为 True,则以某种方式渲染流场块

Rendering streamfield block a certain way if booleanBlock is True

您好,我是 django/wagtail 的新手。我正在处理一个显示以前和当前 work/positions 的关于页面。由于经验量不受限制,因此我已经制作了流场块的位置。这是我的模型的代码。

#Create experience block 
class ExperienceBlockStruct(StructBlock):
    position_title = CharBlock(help_text="Enter a previous position title.")
    description = CharBlock(help_text="Job description")
    current_position = BooleanBlock(required=False, help_text="Check if 
    current position")

class Meta:
    template = 'blocks/experience_block.html'


class ExperienceBlock(StreamBlock):
    experience = ExperienceBlockStruct(icon="form")

这是我使用模型的页面

class About(Page):
    profile_pic = "some image reduced code bc it currently works"
    bio = RichTextField(blank=True)
    resume = "some document reduced code bc it currently works"
    experience = StreamField(ExperienceBlock())
    content_panels = Page.content_panels + [
        ImageChooserPanel('profile_pic'),
        FieldPanel('bio'),
        DocumentChooserPanel('resume'),
        StreamFieldPanel('experience'),
    ]

现在我遇到的问题是如何在不同区域渲染 current_position = True 所在的块,而不是那些没有的块。 我试过了

templates/about.html
{% for block in page.experience %}
  {% if block.current_position %}
    {% include_block block %}
  {% endif %}
{% endfor %}

但这并没有渲染任何东西。我也试过

<div class="experience">
  {% if value.current_position %}
    {{ value.position_title }}
  {% else %}
    {{ value.position_title }}
  {% endif %}
</div>

但这会为每个块创建一个新的 div。我想要实现的是 blocks/experience_block.html

<div>
  Current position(s): {% blocks with current_postion == True %}
</div>   

<div>
  Past position(s): {% blocks with current_postion == False %}
</div>  

我怎样才能实现这样的目标?

您的第一个模板片段几乎是正确的 - 您只需要检查 block.value.current_position 而不是 block.current_position:

{% for block in page.experience %}
    {% if block.value.current_position %}
        {% include_block block %}
    {% endif %}
{% endfor %}

这是因为循环遍历 page.experience 会为您提供一系列 BoundBlock 对象,这些对象告诉您 block_type(在您的情况下总是 'experience')以及块值.有关更详细的说明,请参阅 BoundBlocks and values

您可以在 experience_block.html 模板中做同样的事情(使用 {% for block in value %} 而不是 {% for block in page.experience %})——尽管请注意 Meta 模板定义需要继续ExperienceBlock 而不是 ExperienceBlockStruct,因为这是可以访问要循环的完整列表的那个,而不是单个记录。

为了使事情更整洁,我建议在块上定义一个 get_context 方法,这样您就可以在 Python 代码中而不是在模板中进行数据操作...

class ExperienceBlock(StreamBlock):
    experience = ExperienceBlockStruct(icon="form")

    def get_context(self, value, parent_context=None):
        context = super(ExperienceBlock, self).get_context(value, parent_context=parent_context)
        context['current_positions'] = [block for block in value if block.value.current_position]
        context['past_positions'] = [block for block in value if not block.value.current_position]
        return context

    class Meta:
        template = 'blocks/experience_block.html'

这将使变量 current_positionspast_positions 在模板上可用。