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

时间:2017-05-24 14:51:03

标签: python django jinja2 wagtail wagtail-streamfield

你好我现在是django / wagtail的新手。我正在开展一个显示以前和当前工作/职位的页面。由于经验数量不限,我已经设置了流场区块。这是我的模型的代码。

#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>

但那不会呈现任何东西。我也试过

blocks/experience_block.html

但是为每个块创建一个新的div。我希望实现的目标类似于<div> Current position(s): {% blocks with current_postion == True %} </div> <div> Past position(s): {% blocks with current_postion == False %} </div>

execfile

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

1 个答案:

答案 0 :(得分:0)

您的第一个模板代码几乎是正确的 - 您只需要检查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模板定义需要继续{{1}而不是ExperienceBlock,因为那是有权访问完整列表的人,而不是单个记录。

为了使事情更整洁,我建议在块上定义ExperienceBlockStruct方法,以便您在Python代码中而不是在模板内部进行数据操作...

get_context

这将使模板上的变量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_positions可用。

相关问题