early exit in latte template file?

bernhard
Member | 51
+
0
-

I'm quite new to latte and really like it so far!

One thing that I'm missing is some kind of early exit strategy in my latte file. I've been using php code like this before using latte:

// file imagegallery.php
<?php
if(!$page->images->count()) return;
foreach($page->images as $img) {
  echo "<img src...">
}

I know there is n:if=“…”, but can't I somehow use custom PHP on top of my file to make it execute only if a condition is met? I'm looking for something like this:

// file jobheader.latte
{returnif $page->template !== 'job'}
<h1>Details for Job {$page->title}</h1>
<p>...</p>

Thanks for your help!

Last edited by bernhard (2022-04-14 15:23)

Martk
Member | 661
+
+1
-

The best way is using components (https://doc.nette.org/…n/components):

public function render(): void
{
	if (!$this->count()) {
		return;
	}

	$template = $this->createTemplate();

	$template->render();
}
Marek Bartoš
Nette Blogger | 1275
+
+1
-

Do such conditions ideally before rendering templates. Or extract code into a {define} block, an {if} with {include} is one-liner

Early return would not make much sense in html context:

<h1>
  {returnif true} {* I just broke a tag, lol *}
</h1>
David Grudl
Nette Core | 8228
+
+1
-

There is no such thing in Latte, but you can create an issue for it at GitHub.

bernhard
Member | 51
+
0
-

Thx for your suggestions, I've added an issue: https://github.com/…e/issues/287

mystik
Member | 312
+
+1
-

I think simple if is best solution here:

{if $block->images()->count()}
  <h1>{$block->headline}</h1>
  <div n:inner-foreach="$block->images() as $img">
     ...
  </div>
{/if}

Last edited by mystik (2022-04-20 16:05)

David Grudl
Nette Core | 8228
+
+1
-

You can vote on the name https://twitter.com/…228898848769