Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@davidchc
Created September 12, 2019 12:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidchc/2ddb7f6e3d8f74019f8e1c0367491487 to your computer and use it in GitHub Desktop.
Save davidchc/2ddb7f6e3d8f74019f8e1c0367491487 to your computer and use it in GitHub Desktop.
Criar uma classe de template
<?php
require_once "Template.php";
/*
Exemplo teria uma pasta chamadas templates
*/
$template = new Template('templates');
//Passando dados
$template->set('user', [ 'name' => 'David CHC']);
//Define o nome do arquivo, e retorna para uma variavel
$render = $template->render('user');
//imprime o conteudo
echo $render;
<?php
class Template
{
private $data = [];
private $path;
public function __construct($path='')
{
$this->path = $path;
}
public function set($key, $value)
{
$this->data[$key] = $value;
}
public function render($file)
{
$filename = $this->path.$file.'.php';
if (file_exists($filename)) {
ob_start();
extract($this->data);
include $filename;
return ob_get_clean();
}
}
}
<h1>Usuário: <?php echo $user['name'] ?></h1>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment