I was reading this question over on stackoverflow:
https://stackoverflow.com/questions/104516/calling-php-functions-within-heredoc-strings
and the accepted answer says to do plain PHP templates like this:
template.php:
<html> <head> <title><?=$title?></title> </head> <body> <?=getContent()?> </body> </html>
index.php:
<?php $title = 'Demo Title'; function getContent() { return '<p>Hello World!</p>'; } include('template.php'); ?>
To me the above isn't well structured in the sense that template.php depends on variables that are defined in other scripts. And you're using an include() to execute code when you do include('template.php')
(as opposed to using include() to include a class or a function which isn't immediately executed).
I feel like a better approach is to wrap your template inside a function:
template.php:
<?php function template($title, $content) { ob_start(); ?> <html> <head> <title><?=$title?></title> </head> <body> <?=$content?> </body> </html> <?php return ob_get_clean(); } ?>
index.php:
<?php require_once('template.php'); print template('Demo Title', '<p>Hello World!</p>'); ?>
Is the second approach better? Is there an even better way to do it?