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

Community guidelines

Please keep discussions civil and on-topic. Repeated violations may lead to a temporary ban.

Themes & Styling

How to add automatic 'sizes' attribute for srcset

Solved by pamtbaau View solution

Started by Luap 5 years ago · 2 replies · 424 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 Pedro M, 2 months ago
4 198 2 months ago
Themes & Styling · by Ian, 2 months ago
3 94 2 months ago
Themes & Styling · by Norbert, 2 years ago
11 456 3 months ago
Themes & Styling · by Lukáš Findeis, 3 months ago
0 48 3 months ago
Themes & Styling · by Sebadamus, 4 months ago
5 128 3 months ago