首页 > 解决方案 > 如何将 StreamBlock 内部的 StructBlock 渲染为模板?

问题描述

如何在 carousel_block.html 模板中呈现标题、文本、图像。我无法访问这些。这是我的代码。

我的自定义块

class CarouselBlock(blocks.StreamBlock):
    carousel_items = blocks.StructBlock([
        ('heading', blocks.CharBlock(label='Nadpis', max_length=128)),
        ('text', blocks.CharBlock(label='Text')),
        ('image', ImageChooserBlock(label='Obrázek')),
    ])

    class Meta:
        template = 'cms/blocks/carousel_block.html'

这是我的 html 模板,我想在其中呈现标题、文本和图像

<div id="carouselExampleControls" class="carousel slide" data-ride="carousel">
    <div class="carousel-inner">
    {% for carousel_items in self.carousel_items %}
        {% image carousel_items.value.image max-1920x1080 as image_1920 %}
        <div class="carousel-item {% if forloop.first %}active{% endif %} ">
            <section class="banner-area" id="home" style="background-image: url({{ image_1920.url }})">
                <div class="container">
                    <div class="row justify-content-start align-items-center">
                        <div class="col-lg-6 col-md-12 banner-left">
                            <h1 class="text-white">
                                {{ carousel_items.value.heading }}
                            </h1>
                            <p class="mx-auto text-white  mt-20 mb-40">
                                {{ carousel_items.value.text }}
                            </p>
                        </div>
                    </div>
                </div>
            </section>
        </div>
    {% endfor %}

        <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev">
            <span class="carousel-control-prev-icon" aria-hidden="true"></span>
            <span class="sr-only">Previous</span>
        </a>
        <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next">
            <span class="carousel-control-next-icon" aria-hidden="true"></span>
            <span class="sr-only">Next</span>
        </a>
    </div>
</div>

标签: djangowagtail

解决方案


线

{% for carousel_items in self.carousel_items %}

应该:

{% for carousel_items in self %}

(尽管我建议调用变量carousel_item而不是carousel_items,因为它指的是流中的单个项目。)

cms/blocks/carousel_block.html模板中,self指的是 StreamBlock 值 - 这是一个类似列表的对象,而不是字典,因此它没有carousel_items属性。当你遍历它时,你会得到一个块对象序列,它们有一个block_type(在你的情况下总是'carousel_items'如此,因为这里只有一个可用的块类型)和一个value.


推荐阅读