3. Templating

We use standard PHP templating, which proves to be the fastest way to render. Since technically you can bind any data type to a template, we have an absolute flexible solution. PHP template is a slightly different syntax than standard PHP code and both can be interchanged without penalty. We discourage interchanging syntaxes because it also promotes code that ends up to be confusing to a template developer. In this section we will discover what is good PHP templating practices versus bad ones. Figure 1 shows how to write a conditional statement in PHP templates.

Figure 1. Conditional
<?php if($message): ?>
<span><?php echo $message; ?></span>
<?php elseif($error): ?>
<span><?php echo $error; ?></span>
<?php else: ?>
<span>No Message</span>
<?php endif; ?>

In the figure above you'll notice that we do not use curly brances ( },{ ). The same thing can be said about regular PHP code. In PHP code you should not use colons(:), use elseif() or the endif; syntax. The proper way in PHP code is else if() and curly brances ( },{ ). Another thing you'll notice is that we do not echo HTML in a string. You must create PHP tags only when you are writing PHP code. Figure 2 goes over how we can do looping in PHP template.

Figure 2. Looping
	<?php foreach($names as $i => $name): ?>
	<li><?php echo $i+1; ?>: <?php echo $name; ?></li>
	<?php endforeach; ?>

Using PHP template we must also respect HTML formating. In the figure above we tab the foreach because it is inside of a ul tag. Oppositely HTML can ignore PHP formatting, because PHP does not show in the end result, we need to pretend that it's not there. From the figure above, you'll see the li tag on the same tab level as the foreach. It's also encouraged to use partials as much as you can to prevent having to build the same template formats across diferent pages and to reduce the amount of tab levels found in a single template. Figure 3, shows how we can simply call a partial template.

Figure 3. Partial
<?php include __DIR__.'/_menu.phtml'

There will be times where you'll need to access data outside of the binded values. All front application template files have access to the front() function and all template files not application specific has access to the eden() function. This is why it's encouraged to build custom helper methods in the Front class found in front.php. Figure 4 shows how we can easily access both functions within a template.

Figure 4. Application Access
<?php echo eden('type', $row['post_title'])->dasherize(); ?>
<?php echo front()->registry()->get('server', 'HTTP_HOST'); ?>
<?php echo front()->path('web'); ?>

© 2012 Openovate Labs. All rights reserved.