Skip to content

PHTML View Templates

Devin Smith edited this page Feb 3, 2016 · 4 revisions

.phtml differs from .php in that it is primarily for templating and views rather than scripts or code. The language itself is the same, however in phtml, it is mostly html, rather than php. This helps separate your types of code so that frontend and backend developers can better find what they need.

PHP Short Tags

Because most of the code is html, it is common to use Short Tags.

<?php echo $something ?>			// A normal opening tag, output, and closing
<?=$something?>						// A short tag, output, and closing

For more information on how to enable them if you don't already have them, see PHP Short Tags

Alternative syntax for control structures

Reading html and looking for closing braces, it can be a pain. I recommend using the alternative syntax to make the code more readable.

Normal syntax
<? if (1 == 1) { ?>
	Duh.
<? } ?>
Alternative syntax
<? if (1 == 1) : ?>
	Duh.
<? endif; ?>

Examples

PHP only example

// assign the data
$friends = ['bob','jim','katie'];

// loop through the data and output
echo '<div class="friends">';

foreach ($friends as $friend) {
	echo '<b>'.$friend.'<b> is my friend.<br>';
}

echo '</div>';

PHP & PHTML Example

friends.php
$Scope->friends = ['bob','jim','katie'];
$View->display('friends');
friends.phtml
<div class="friends">
	<? foreach ($friends as $friend) : ?>
		<b><?=$friend?><b> is my friend.<br>
	<? endforeach ; ?>
</div>