Automatically apply custom template to a block type when added to an area?

Permalink 3 users found helpful
Is it possible to automatically apply a custom template when a certain type of block is added to specific area?

Standard behaviour is to add the block, then select the custom template from the drop-down list, but I'm trying to make this as foolproof as possible for my client.

Thanks :)
J.

builtbyjay
 
builtbyjay replied on at Permalink Best Answer Reply
builtbyjay
Had a bit of brainwave and figured it out myself. For anyone else seeking the solution:

<?php  
$a = new Area('Grid Panels');
//If not in edit mode...
if (!$c->isEditMode()):
   //Get all blocks within the area
   $blocks = $c->getBlocks('Grid Panels');
   foreach($blocks as $b):
      //If block type is an image, use the custom template.
      if ($b->btHandle == 'image')
         $b->display('templates/custom_template_name');
      else
         $b->display();
   endforeach;
else:   
   $a->display($c);


Voila.
formigo replied on at Permalink Reply
formigo
*** Edit - I was just answering it too. Approach below is different to yours, would be theme independent **

This isn't tested, but this where I would start.

For each block you wanted this control over, you would override each block's controller.

In each controller, probably in your view() method, you would get the
area the block was loaded in like this, based on that apply your 'which template to use' logic.

$bID = $this->bID;
$block = Block::getByID($bID);
$area = $block->getAreaHandle();
if($area == 'this_area') {
  $template = 'template 1';
} else {
  $template = 'template 2';
}
$this->render($template);


I think that would work.

Best

Ollie
builtbyjay replied on at Permalink Reply
builtbyjay
Ooo, nice approach actually. I like the fact it doesn't muddy up the page type code, and I can see the advantage of it being theme independent.

One thing though - as you're already within the Block's view.php, you don't need to create another object for the block - the object with the getAreaHandle() function is already available to you. Replace your first 3 lines of code with this:

$area = $this->block->getAreaHandle();


Thanks for the assistance Ollie :)