Connecting the template to PHP.

I’m interested in the question of how to correctly and better implement the connection of the template to the php code. I would like the template to be in a separate folder. What are the best ways to go? Inclusions or otherwise…


Answer 1, authority 100%

I just ran into the fact that if the template files are in a different folder, then when included, neither style files, nor pictures, nor sprites are connected at all. And this is understandable, since the dance comes from the called file.

So what’s the problem, specify absolute paths. Not "../css/style.css", but "/css/style.css"or "http://mysite.com/css/style.css"

<link rel="stylesheet" type="text/css" href="/css/style.css" />

Again, maybe this will help you:

define('TPL_PATH', '/templates/');
define('TPL_PATH_FULL', $_SERVER['DOCUMENT_ROOT'].TPL_PATH);
function wrapFile($file, $templateID) {
  if (!file_exists($file)) die('No File!');
  if (!file_exists($tpl = TPL_PATH_FULL.$templateID.'.tpl')) die('No Template');
  $TEMPLATE_DIR = TPL_PATH.$templateID.'/'; // /templates/mypage/
  ob_start();
  require $file;
  $CONTENT = ob_get_contents();
  ob_end_clean();
  ob_start();
  require $tpl;
  $ret = ob_get_contents();
  ob_end_clean();
  return $ret;
  }
// wrapFile(__FILE__, 'mypage')

And use paths in the template

<link rel="stylesheet" type="text/css" href="<?=$TEMPLATE_DIR?>css/style.css" />
<!--   /templates/mypage/css/style.css -->

Answer 2

Here is a very interesting article on this topic: Template Engines


Answer 3

only includes, if you don’t want to parse HTML from PHP, you can use a template engine, but then your project will take up a relatively large amount of space (which is very critical if you write some kind of engine), but if you still calmly parse ” mixed” code, I advise you to just create a template file


Answer 4

$fgc = file_get_contents('dir/file.html');
$fgc = str_replace('{title}',' ' $fgc);
$fgc = str_replace('{body}',' ' $fgc);
echo $fgc;
// file.html
<html>
<head>
<title>{title}</title>
</head>
<body>
{body}
</body>
</html>

Absolutely simple example


Answer 5

how else? Use the inclusions!
By the way, I recommend Smarty (http://smarty.net) as a templating engine