Home > Back-end >  I need to write an if statement for adding an image next to an h1 tag in an unordered list, if the i
I need to write an if statement for adding an image next to an h1 tag in an unordered list, if the i

Time:02-04

Attached is the wagtail template I have written so far.

{% load wagtailimages_tags %}

<section >
    <h2 >{{ self.title }}</h2>
    <div >
        {% for member in self.general_member_cards %}
            {% if member.photo %}

            {% endif %}
        {% endfor %}
    </div>
</section>

Ultimately I want the code to look like

<h2>Avatar Images</h2>

<ul>
    <li><img src="img_avatar.png" alt="Avatar" > <h3> Bleu </h3></li>
    <li><img src="img_avatar2.png" alt="Avatar" > <h3> Red </h3></li>
</ul>

</body>
</html>

with the image popping up next to the "h3" tag if there exists a photo of course the image will be {{}} double bracketed for dynamic template.

Image of what I want but need to know how to achieve in django templates

CodePudding user response:

It's not clear whether the image is from Wagtail's image library, but if it is, you should use the {% image %} tag. See https://docs.wagtail.org/en/stable/topics/images.html#

{% with self.general_member_cards as cards %}
{% if cards %}
    <ul>
        {% for member in cards %}
            <li>
                {% if member.photo %}
                    {% image member.photo fill-80x80 %}
                {% endif %}
                <h3>{{ member.name }}</h3>
            </li>
        {% endfor %}
    <ul>
{% endif %}

I have also used a {% with %} tag to cache self.general_member_cards in the template, in case this requires a database query. If it does not, you can skip that step.

CodePudding user response:

You more or less have it already ...

<section >
    <h2 >{{ self.title }}</h2>
    <div >
        <ul>
        {% for member in self.general_member_cards %}
            <li>
            {% if member.photo %}
                <img src="{{ member.photo.url }} class='avatar">&nbsp;
            {% endif %}
            <h3 style="display:inline;">{{ member.name }}</h3>
            </li>
        {% endfor %}
        </ul>
    </div>
</section>

You said you wanted image next to the <h3>, so you need to override the display:block property of the h3 tag and make it inline as above (or create a css class for this).

  • Related