PHP Latte - multiple block with same name

473 Views Asked by At

I am new to latte template engine and fiddle around with it since some days. I found a lot of nice and usefull things to make my projects easier and cleaner. But there is one thing I did not find or miss an idea how to handle it.

Lets imagine my sites has this basic layout template:

<header><h1>{$title}</h1></header>
<nav n:inner-foreach="$navigation as $link">
<a href="{$link->url}" n:class="$link->active ? active" n:attr="data-icon: $link->icon">{$link->name}</a>
</nav>
<aside>{include aside}</aside>
<aside>{include aside}</aside>
<aside>{include aside}</aside>
<content>{include content}<content>
<footer>{include footer}</footer>

the content is handled within another template for each site. every one of them looks like this:

{layout 'layout.tpl'}
{$navigation[3]->active=true}
{$title="this page title"}

{block content}
    <p>here comes the content</p>
{/block}

{block aside}
    <p>here is f.e. a sidebar</p>
{/block}

{block aside}
    <p>this is some adverticement</p>
{/block}

now my question is this: how can I use one or more blocks of "aside" within my template which are defined as "block". the best solution whould be something like: "block aside[]" and I handle it inside the main template somehow with a loop. Is there an usefull way to do it? I dont want to use it with variables like the navigation because the content is defined within the template.

thx for ideas and greetings Makka

1

There are 1 best solutions below

6
On

Well, you could do something like, abusing dynamic block names:

{var $maxAside = 10}
{for $i = 0; $i < $maxAside; $i++}
  {ifset aside-$i}
    {include "aside-$i"}
  {else}
    {breakIf true}
  {/ifset}
{/for}

and define blocks like {block "aside-{++$i}"}…{/block} but I would not recommend this because it just adds pointless complexity.

Either, majority of the asides will be the same and then you could have just used a single aside block for them:

{block aside}
  <section>
    <p>here is f.e. a sidebar</p>
  </section>

  <section>
    <p>this is some adverticement</p>
  </section>
{/block}

Or you you will want to be distinguishing them somehow (e.g. styling them differently) and then you would assign them classes, at which point you can just use different blocks:

<aside class="sidebar" n:ifset="sidebar">{include sidebar}</aside>
<aside class="advertisement" n:ifset="advertisement">{include advertisement}</aside>

Unless you are matching them using :nth-child CSS selector. But that is fragile because you would now need to match the order to the one defined in the CSS.


The problem only starts to become interesting when you have a hierarchy of pages where the pages inherit asides from pages in parent layers. But then it is still nicer to use template inheritance.