Compose CSS class strings based on content selection

Hi there,

I'm using a replicator fieldset to allow laying out fields in two columns. Editors can decide the columns' distribution by choosing beteween 33_66, 50_50 and 66_33 from a button group.

From twig I'm used to taking this selection as the basis for some variables that I then use to build my columns, e.g.

{% if layout == '33_66' %}
    {% set column_1_classes = 'w-1/3' %}
    {% set column_2_classes = 'w-2/3' %}
{% endif %}

As antlers doesn't support setting variables like this I thought maybe ViewModels are the way to go, yet I don't get them to work for this scenario – and I'm unsure if it's even intended.

I'm already stuck rendering a string returned from my ViewModel in the template.

resources/fieldsets/columns.yaml

title: Columns
inject:
  view_model: App\ViewModels\ColumnLayout
fields:
  -
    import: spacing
  -
    handle: column_layout
    field:
      options:
        '33_66': 33/66
        '50_50': 50/50
        '66_33': '66/33'
      display: Spalten-Layout
      type: button_group
      icon: button_group
      listable: hidden
  -
    handle: column_1
    field:
      collapse: false
      sets:
        text:
          display: Text
          fields:
            -
              import: text
        image:
          display: Image
          fields:
            -
              import: image
      display: 'Spalte 1'
      type: replicator
      icon: replicator
      listable: hidden
  -
    handle: column_2
    field:
      collapse: false
      sets:
        text:
          display: Text
          fields:
            -
              import: text
        image:
          display: Image
          fields:
            -
              import: image
      display: 'Spalte 2'
      type: replicator
      icon: replicator
      listable: true

app/ViewModels/ColumnLayout.php

<?php

namespace App\ViewModels;

use Statamic\View\ViewModel;

class ColumnLayout extends ViewModel
{
    public function data(): array
    {
        return [
            'foo' => 'bar'
        ];
    }
}

resources/views/partials/sets/columns.antlers.html

<h1>ViewModelOutput: {{ foo }}</h1>

<div class="{{ margin_top }}">
    <div class="o-container">
        <div class="{{ column_parent_classes }} -mx-4">
            <div class="w-1/2 px-4">
                {{ column_1 }}
                    {{ partial src="sets/{type}" }}
                {{ /column_1 }}
            </div>

            <div class="w-1/2 px-4">
                {{ column_2 }}
                    {{ partial src="sets/{type}" }}
                {{ /column_2 }}
            </div>
        </div>
    </div>
</div>

Expected Result: {{ foo }} is 'bar'

Actual Result: {{ foo }} is empty

I'm open to any suggestion how to best solve this without messing up my templates with too many conditions, no matter if its by using ViewModels or any other method.

>>>>>>> Unanswered <<<<<<<
2 Replies
2 Followers