RobMcC
RobMcC

Reputation: 412

Getting url of image on django/wagtail site

I have a wagtail site - where blogpages are rendered by looping through a streamfield (in which each block can have an image, a heading and some text):


<div class="col-md-8 mx-auto px-auto">
    <div class="conundrum mb-3">{{ page.category }}</div>
    <h1>{{ page.title }}</h1>
    <p class="meta">{{ page.date }}</p>
    <div class="intro my-4 py-4">{{ page.intro }}</div>

    {% for block in page.content %}
        <div class="pb-4">
        {% image block.value.image fill-1000x500 class='blog_image' %}
        <h2 class="py-2 my-2">
            {% include_block block.value.heading %}
        </h2>
        {% include_block block.value.text %}

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

I want the 'tweet this' button on the blogpage to include the first image on that page.

<meta name="twitter:card" content="summary" />
<meta name="twitter:site" content="@PsymatikDotCom" />
<meta name="twitter:title" content="{{page.title}}" />
<meta name="twitter:description" content="{{page.intro}}"/>
<meta name="twitter:image" content="https://how_do_i_get_this_path" />

But it is not clear to me how to dynamically grab the url of the first image to enter it in the twitter:image section?

Upvotes: 1

Views: 2281

Answers (3)

winning godspower
winning godspower

Reputation: 21

Was also having this issue. But i think i found the answer. It's simple

{{ page.image.file.url }}

Upvotes: 2

user3673451
user3673451

Reputation: 33

For each Image object Wagtail creates several Rendition objects, in accordance all your registred formats, so you need to refer to the Rendition object for a link to a specific image

Your case:

templatetags.images.py

from django import template
from wagtail.images import get_image_model
from wagtail.images.models import Rendition

Image = get_image_model()
register = template.Library()


@register.filter(name="get_img_src")
def get_img_src(img: Image, spec: str) -> str:
    if not img:
        return ''

    rendition = img.get_rendition(spec)
    return rendition.attrs_dict['src']

template.html

<meta name="twitter:image" content="{{ block.value.image|get_img_src:"your_spec" }}" />

Upvotes: 1

LB Ben Johnston
LB Ben Johnston

Reputation: 5176

See the Wagtail docs page on How to use images in templates.

<head>
  {% image page.photo width-400 as tmp_photo %}
  <meta name="twitter:image" content="{{ tmp_photo.full_url }}">
</head>

You can combine this approach with the first Django template filter.

<head>
{% with page.content|first as first_block %}
  {% image first_block.value.image width-400 as tmp_photo %}
  <meta name="twitter:image" content="{{ tmp_photo.full_url }}">
{% endwidth %}
</head>

Upvotes: 4

Related Questions