Outsource function to controller

Sorry for a probably very basic question but I’m not a native PHP programmer.
I have this code in my template:

<ul class="overview">
		<?php
			foreach($posts as $post):
				if($post->slug() !== $featured->slug()):
					$hasPostImage = $post->post_image()->toFile();
					$color_class = null;
					if(!$hasPostImage):
						$post_color = $post->post_color();
						$post_color = $post_color->value();
						switch($post_color) {
							case "#8F3D97":
								$color_class = 'purple';
								break;
							case "#3E51A3":
								$color_class = 'blue';
								break;

							…

							default:
								$color_class = 'red';
								break;
						}
					endif;
		?>
	<li class="<?php e(!$hasPostImage,' noimg '.$color_class); ?>">
		<a href="<?= $post->url(); ?>">
			<?php e($hasPostImage,$hasPostImage); ?>
			<span><?= $post->title()->html(); ?></span>
		</a>
	</li>
	<?php
			endif;
		endforeach;
	?>
</ul>

I have a post_color field in the blueprint where various HEX values can be selected, to convert them to class names in the generated HTML, so that the elements can be styled accordingly in the stylesheet.

How would I outsource this switch statement and the whole post color logic to a controller? The controller example in the documentation is pretty basic and doesn’t help me very much.

Any help is greatly appreciated

You can define a standard php function in your controller or in a plugin, and while you are at it, might as well put some more code into the controller.

return function($page) {

    $featured = $page->featuredPage()->toPage();
    $posts = $page->children()->listed()->not($featured);

    function getColorClass($page){
        $colorClass = null;
        $postColor = $page->post_color();
        
        // your logic here
        return $colorClass;
    }

    return [
        'posts' => $posts
    ]; // array of variables you want to return to your template
}

Then in your template within the foreach loop:

<?php echo getColorClass($post) ?>

(You could also create a page model or page method to get the color class)

1 Like

Thanks, this works nicely. :slight_smile: