Returning from a template

Ever needed to return from a template earlier than at its end? Exit in the middle or even at the very beginning because you don’t want to print the rest of the template?

For me this is a preferred way of distributing the presentation logic. Say you have a template for printing messages and you use it on every page. It starts with a header and then prints all messages from your stack. But you don’t want the header when there are no messages.

You can either wrap each include with an if or put the if statement into the element template itself. The latter is cleaner, no doubt.

But that brings another question. Do you really want to wrap your whole template in that if?

  1.  
  2. {if count($messages)}
  3.   very
  4.   many
  5.   lines
  6.   …
  7.   oh, what’s this /if for?
  8. {/if}
  9.  

Of course not, you want to exit at the very top.

  1.  
  2. {if empty($messages)}
  3.   {? return}
  4. {/if}
  5.  
  6. continue with the very many lines
  7.  

In other words: check for exceptional situations at the top and continue only if everything is all right. Such code tells its story in a clearer way. Especially when you need to check for many exceptional states.

The above example is in Nette/Latte syntax. Here’s Smarty:

  1.  
  2. {if !$messages|@count}
  3.   {php}return;{/php}
  4. {/if}
  5.  

Leave a Reply