Added simple templates module

This commit is contained in:
Antonio de la Rosa 2025-11-23 01:26:30 +01:00
parent 47c7003e3b
commit 17b6df73ff
7 changed files with 265 additions and 38 deletions

View file

@ -0,0 +1,153 @@
<?php
namespace PhaTemplates;
class Templates {
public $search_dir;
public $template='';
public $section='';
public $section_content=[];
public $yes_layout=false;
public $layout='';
public function __construct($search_dir) {
$this->search_dir=$search_dir;
}
public function load_template($name_template, $args=[]) {
$name_template=basename($name_template);
$template='';
$this->yes_layout=0;
//$yes_template=false;
$z=0;
foreach($this->search_dir as $dir) {
$file_template=$dir.'/'.$name_template.'.php';
if(is_file($file_template)) {
extract($args);
ob_start();
include($file_template);
if($this->yes_layout) {
//$sections_layout=implode("\n", $this->section_content);
$final_template=$this->load_template($this->layout, $args);
echo $final_template;
}
$this->template=ob_get_contents();
ob_end_clean();
break;
}
else {
if($z==count($this->search_dir)) {
throw new \Exception("Error: view {$file_template} not found: ".implode(' and ', $this->search_dir));
die;
}
}
$z++;
}
return $this->template;
}
/**
* Method for set a layout in the template
*
*/
public function layout($tpl_name, $args) {
//echo implode("\n", $this->section_content);
$this->yes_layout=true;
$this->layout=$tpl_name;
}
/**
* Method for set a section in a layout
*
*/
public function section($section_name) {
//First execute start and end
if(isset($this->section_content[$section_name])) {
echo $this->section_content[$section_name];
}
else {
echo $section_name.' dont have any content';
}
}
/**
* Method for create a section in a template with a layout
*
*/
public function start($section_name) {
ob_start();
}
/**
* Method for finisha section in a template with a layout
*
*/
public function end($section_name) {
$this->section_content[$section_name]=ob_get_contents();
ob_end_clean();
}
public function e($str) {
return html_entities($str);
}
}