Create an object that can be passed to a snippet

Dear Kirby forum,

for the template “team” I created the snippet “card-employee” which prints business cards of each employee. It simply takes a kirby page as parameter. Now, I want to reuse this snippet in the template “contact” which lists internal persons of our team as well as external institutions. While I can simply pass the internal persons as page again, I fail in building and passing an object reflecting the institutions. Note: I’m collecting the details of the institutions on the ‘contact’ page of the panel using the same fields as for the employees.

  • My first idea: Use new Page() and pass the institution details to the content object. This works perfectly fine. However, new Page() creates a new file in the file system. But I only want to pass on the details to the snippet.

  • I also tried to pass the details as php object. However, I’m not able to use member functions like in $employee->img()->isNotEmpty()

  • My next idea: Use new Content() to create a new Content object with the institution details. However, I fail because I don’t have access to the class(?).

Below you can see my current code. I am looking forward to your suggestions.

Many thanks
Alexander

<?php if ($page->contacts()->isNotEmpty()) {
	$contacts = $page->contacts()->toStructure();
	foreach ($contacts as $c) {
		echo '<div class="col-12 col-md-6 d-flex flex-column">';
		if ($c->type() == 'internal') {
			$employee = $c->internal()->toPage();
			snippet('partials/headline', ['text' => $c->title()]);
			snippet('card-employee', ['employee'=>$employee, 'class'=>'h-100']);
		} elseif ($c->type() == 'external') {
			// Class "Content" was not found, that's why I'm trying to include it
			// Result: Cannot declare class Kirby\Cms\Content, because the name is already in use
			include('kirby\src\Cms\Content.php');
			$employee = new Content([
				'img' => 'a-picture.png',
				'cardName'  => $c->cardName(),
				'cardPosition' => $c->cardPosition(),
				'cardRoom' => $c->cardRoom(),
				'cardTel' => $c->cardTel(),
				'cardMail' => $c->cardMail()
			]);
			snippet('partials/headline', ['text' => $c->title()]);
			snippet('card-employee', ['employee'=>$employee, 'class'=>'h-100']);
		}
		echo '</div>';
	}
}?>

Don’t include the class but use the FQN:

$employee = new Kirby\Cms\Content([
  'img' => 'a-picture.png',
  'cardName'  => 'Per Boider',
  'cardPosition' => 'Head of sales',
  'cardRoom' => '543',
  'cardTel' => '',
  'cardMail' => 'peter@tel.de'
]);

Alternatively, use a use statement at the top of the file and then the short name:

use Kirby\Cms\Content;
//....

$employee = new Content([
  'img' => 'a-picture.png',
  'cardName'  => 'Per Boider',
  'cardPosition' => 'Head of sales',
  'cardRoom' => '543',
  'cardTel' => '',
  'cardMail' => 'peter@tel.de'
]);
1 Like

Thanks a lot, it works!