Forum

Thread tagged as: Suggestions, Showcase, Discussion

Perch 2: Creating related content using 'each'

This was originally going to be a "how do I...?" but managed to figured it out. Wanted to post in case useful for others!

First, some context...

  • I have a page with a list and detail of treatments, e.g. 'Osteopathy'
  • I have another page with a list and detail of therapists, e.g. 'Dr. Awesome'
  • Each treatment contains a repeater to cater for multiple sub-types, e.g. Spinal Osteopathy, Cranial Osteopathy
  • Each treatment sub-type has an associated therapist
  • I didn't want the client to have to upload therapist data twice

For this, each came in useful - the ability to manipulate Perch data prior to template render: https://docs.grabaperch.com/docs/content/perch-content-custom/#specifying-an-item-callback-function

Liberally commented example to pull just the therapist image across from another region - but it could be used for all/any 'related' data:

// Treatment detail mode
perch_content_custom('Treatments', 
  array(
    'template' => 'treatment-detail.html',
    'filter' => 'slug',
    'match' => 'eq',
    'value' => perch_get('treatment'), // filter by querystring ID/value
    'count' => 1,

    // Related Therapists
    'each' => function($item) { // manipulate template data...

      $i = 0; // need index reference point for setting data back to associative array

      foreach($item['treatment'] as $treatment) { // there can be multiple treatments

        $therapistName = $treatment['therapist-name']; // unique 'ID' to query Perch

        if ($therapistName) { // therapist selected from dataselect? (can be blank)

          // fetch related therapist data
          $data = perch_content_custom('Therapists', array(
            'page' => '/therapists.php',
            'skip-template' => 'true',
            'filter' => 'therapist-name',
            'match' => 'eq',
            'value' => $therapistName
          ));

          // pop image into therapist-image template field
          $item['treatment'][$i]['therapist-image'] = $data[0]['therapist-image'];
        }

        $i++; // Increment treatment index
      }

      return $item; // ...then send it back to template
    }
  )
);

Then in treatment-detail.html we have <perch:content id="therapist-image" type="hidden" /> as a sort-of placeholder for the image data we create, hidden from the admin view.

Much easier to achieve in Perch Runway with the Related Content feature - but, in this instance, needed to achieve the same with regular ol' Perch.

Hope it might help somebody!

Please note: this not optimal in terms of performance so use sparingly/wisely

Keir Moffatt

Keir Moffatt 0 points

  • 6 years ago

Thanks, Keir,

Caught your conversation with Drew M. Funny and interesting- thank you!

Very welcome, hope it is helpful. Drew makes me do the LOLs.