How would you access this structure in a template?

I’m new to Kirby and from what I’ve read the structure field has very limited utility. Is it possible to use the structure field in this way? If so, how would you do it?

membershipType2:
  heading: Month-to-month
  options:
  -
    commitment: 10 hours / month
    rate: $275 / month
  -
    commitment: 15 hours / month
    rate: $350 / month

----

No, you can’t nest the structure field. Structure fields will look like this in the content file:

https://getkirby.com/docs/cookbook/the-structure-field#structure-field-entries-in-the-content-file

So, if you leave out the heading and option keys, which are not really necessary, as you can put them into your template, you will be fine.

membershipType2:
-
  commitment: 10 hours / month
  rate: $275 / month
-
  commitment: 15 hours / month
  rate: $350 / month

In your template (example):

<h1> Membership types</h1>
<h2> Month-to-month memberships</h2>
<?php
$options = $page->membershipType2()->toStructure();
foreach($options as $option) {
  echo $option->commitment() . ': ' . $option->rate();
}
?>

An alternative would be to put all sorts of memberships into one structure field with more fields, then you are more flexible anyway. You can then filter your options in your template.

Blueprint:

membershiptypes:
  label: Membershiptypes
  type: structure
  fields:
    membershiptype:
      label: Type of Membership
      type: select
      options:
        monthly:  Monthly
        yearly: Yearly
        whatever: Whatever Else
     commitment:
       label: Commitment
       type: text
     rate:
       label: Rate
       type: text

To output these in your template, you can then filter by the different types:

$membershipType1 = $page->membershiptypes()->toStructure()->filterBy('membershiptype', 'monthly');
// etc.
1 Like

you could also access the structure as an array using yaml(). but its less intuitive but has its use when updating a structure programatically. like dividing by half…

$options = $page->membershipType2()->yaml();
foreach($options as $optionkey => $optionvalue) {
  if($optionkey == 'commitment') {
    $hours = intval(explode(' ', $optionvalue)[0]); // just example. not good style.
    $options[$optionkey] = round($hours / 2) . ' hours / month';
  }
}
try{
  $page->update(['membershipType2' => $options]);
} catch(Exception $ex) {
 echo $ex->getMessage();
}
1 Like

This answer solved my problem – thanks a ton!