nakome
10/28/2017 - 3:07 PM

Very simply templating

Very simply templating

<!Doctype html>
<html>
	<head>
		<title>Test template</title>
	</head>
	<body>
		<h1>${title}</h1>
		<p>${description}</p>
		<p>${body}</p>
		<p>${footer}</p>
	</body>
</html>
<?php

/**
 *  Thm class
 * @version  1.0
 * @author Moncho Varela <nakome@gmail.com>
 */
class Thm {
	/**
	 *  Render Template
	 * 
	 * 	<code>
	 * 		$Thm = new Thm();
	 * 		$Thm->render('test.html',$array);
	 * 	</code>
	 * 
	 * @param string $file
	 * @param array $args
	 * 
	 * @return string
	 */
	public function render($file= '', $args = array()){
		extract($args);
		// check if exits
		if(is_file($file)){
			header('content-type: text/html');
			$out = file_get_contents($file);
			foreach($args as $k => $v){
				$arr = ($args[$k]) ? $args[$k] : '';
				if(array_key_exists($k, $args)){
					$out = str_replace('${'.$k.'}',$arr,$out);
				}
			}
			echo $out;
		}
	}
}

// init
$html = new Thm();
// array
$array = array(
	'title' => 'Hello World',
	'description' => 'This is a description',
	'body' => '<pre>console.log("hello world")</pre>',
	'footer' => 'Copyright &copy; 2017'
);
// render
$html->render('test.html',$array);