Skip to content
Grav 2.0 is officially stable. Read the announcement →
Themes & Styling

How to add automatic 'sizes' attribute for srcset

Solved by pamtbaau View solution

Started by Luap 5 years ago · 2 replies · 539 views
5 years ago

I am building an image module and want to give editors the possibility to choose a fullscreen or split layout. Adding a class for the styling is not the issue, but I am struggling to set the sizes attribute for srcset. I imagine it's a relatively easy if-statement. So that the sizes is set to either 100vw or 50vw, depending on the selected class (or any other admin panel control).

Here's my twig

TWIG
<section class="image {{ page.header.imagelayout.class }}">
    {% for image in page.media.images %}
        <div class="projectimage projectimage__half">
            {% set service_image = image.derivatives(750,2900,700).enableProgressive().sizes('100vw') %}
            <img 
            data-src="{{ service_image.url(false) }}"
            data-srcset="{{ service_image.srcset(false) }}"
            sizes="{{ service_image.sizes(false)}}">
        </div>
    {% endfor %}
</section>

Here's a added class I was trying to use to "convert" to either 50vw or 100vw

YAML
header.imagelayout.class:
  type: select
  label: Layout
  size: medium
  default: Side by Side
  help: 'Image layout next or below to each other'
  options:
    image__layout--half: Side by Side
    image__layout--full: Below each other
5 years ago Solution

@luap, You could try the following:

TWIG
<section class="image {{ page.header.imagelayout.class }}">
  {% for image in page.media.images %}
    <div class="projectimage projectimage__half">
      {% set size = header.imagelayout.class == 'image__layout--half' ? '50vw' : '100vw' %}
      {% set service_image = image.derivatives(750,2900,700).enableProgressive().sizes(size) %}
      <img 
        src="{{ service_image.url(false) }}"
        srcset="{{ service_image.srcset(false) }}"
        sizes="{{ service_image.sizes(false)}}">
    </div>
  {% endfor %}
</section>

By the way, you could generate the <img> tag using:

TWIG
{{ service_image.html() | raw }}
last edited 10/11/21 by pamtbaau
5 years ago

@pamtbaau thank you! This is working very nicely

Suggested topics

Topic Participants Replies Views Activity
Themes & Styling · by stuart young, 2 weeks ago
3 251 2 weeks ago
Themes & Styling · by Sebadamus, 3 weeks ago
5 317 3 weeks ago
Themes & Styling · by martynfoster735, 4 weeks ago
1 310 4 weeks ago
Themes & Styling · by Justin Young, 1 month ago
1 348 1 month ago
Themes & Styling · by Slebeig, 2 months ago
4 474 2 months ago