How to access the image of a ImageChooserBlock in Template

1,324 views
Skip to first unread message

Magdalena Noffke

unread,
Mar 7, 2016, 10:27:29 AM3/7/16
to Wagtail support
Hi there,

 I am a bit confused at the moment and I guess there is an esay answer to that question:

So, have a Page that includes a Streamfield: 

body_en = StreamField([
        ('heading', blocks.CharBlock(classname="full title", icon="title")),
        ('paragraph', blocks.TextBlock(icon="pilcrow")),
        ('rich_text', blocks.RichTextBlock(icon="pilcrow")),
        ('info_block', InfoBlock()),
        ('image', ImageChooserBlock(icon="image")),
        ('wide_image', WideImageBlock(icon="image")),
        ('images', InlineImagesBlock(icon="image")),
        ('contact_block', ContactBlock(icon="form")),
        ('accordion_block', AccordionBlock(icon="collapse-down")),
        ('image_text_block_list', ImageTextBlockList())
    ], null=True, blank=True, verbose_name="body")

Within this Streamfield I use the build-in ImageChooserBlock ( meaning it does not have its own template)

So now I have something like that in my template

{% for block in self.body %}
    {% if block.block_type == 'heading' or block.block_type == 'paragraph' or block.block_type == 'rich_text' or block.block_type == 'image' %}
    <div class="block-inner">
        <div class="container">
            <div class="container-narrow">
            {% if block.block_type == 'image' %}
                {{ block }}
            {% elif block.block_type == 'heading' %}
                <h2>{{ block.value }}</h2>
            {% else %}
                {{ block.value }}
            {% endif %}
            </div>
        </div>
    </div>
    {% else %}
        {{ block.value }}
    {% endif %}
{% endfor %}

But I would like to use a Imagetag for the image, in order to style it, but I cannot get the ImageTag to work, as I don't know hoe to access the image. How can I do that?

Thanks,
Magda

Matthew Westcott

unread,
Mar 7, 2016, 10:37:14 AM3/7/16
to wag...@googlegroups.com
Hi Magda,

The image object is available as block.value - so you can do:

{% load wagtailimages_tags %}
...
{% if block.block_type == 'image' %}
{% image block.value fill-800x600 %}
{% endif %}

or, for full control over the <img> tag HTML:

{% load wagtailimages_tags %}
...
{% if block.block_type == 'image' %}
{% image block.value fill-800x600 as my_image %}
<img class="photo" src="{{ my_image.url }}" width="{{ my_image.width }}" height="{{ my_image.height }}">
{% endif %}

Cheers,
- Matt

Magdalena Noffke

unread,
Mar 7, 2016, 10:49:11 AM3/7/16
to Wagtail support
Hey Matt,

I thought, I tried this, but apparently I didn't :-)

So thanks a lot!
Reply all
Reply to author
Forward
0 new messages