How do I add a variable to 'srcset'?

I’m struggling to add a variable in my template to ‘srcset’, although the value is displayed with dump. My goal is to select the aspect ratio for the image output in the panel and pass it to the template.

(The code is reduced to the essentials for a better overview)

blueprints/blocks/image.yml

  imageratio:
    type: toggles
    options:
      - value: "'square'"
        text: "quadratisch"
      - value: "'1500x1000'"
        text: "3:2"
      - value: "'1800x900'"
        text: "2:1"

snippets/blocks/image.php

<?php
$ratio = $block->imageratio();
?>

<img src="<?= $image->resize(600)->url() ?>" 
srcset="<?= $image->srcset($ratio) ?>"
sizes="(min-width: 1200px) 25vw, 
       (min-width: 900px) 33vw, 
       (min-width: 600px) 50vw, 100vw" 
width="<?= $image->resize(600)->width() ?>" 
height="<?= $image->resize(600)->height() ?>" 
alt="<?= esc($alt, 'attr') ?>">

There is no value in the source code:

srcset=""

However, a value is output with dump:

<?= dump($ratio) ?>

Kirby\Content\Field Object
(
    [imageratio] => 'square'
)

Where is the error? :thinking:

You are passing a field object instead of a string. Should be

$ratio = $block->imageratio()->value();

Thanks for your answer.
With dump only the value 'square' is now output.
But it still does not work with
srcset="<?= $image->srcset($ratio) ?>"

Nothing is output in the source code:
srcset=""

The hardcoded notation works as desired.
srcset="<?= $image->srcset('square') ?>"

:man_shrugging:

Is that a defined preset?

Yes, in the confiq.php based on the cookbook

The problem are the quotes

Great, that works :clap:
But I would also like to understand why it only works with hardcoded apostrophes srcset="<?= $image->srcset('square') ?>" and with a variable srcset="<?= $image->srcset($ratio) ?>" only without apostrophes?

  1. These are single quotes, not apostrophes.
  2. You need the quotes when you use a hard-coded string, to denote it as string, but not if a variable is already a string. So in your case, as you see when you dump the variable, it contains quotes as part of the value, while it may not.

Thank you very much for the explanation.
And again I have learned something new.
I’ll save that directly to my SnippetsLab app.