For a project, I need to write a basic template manager who will be responsible to load the requested HTML or PHP template when the user clicks on a menù link. It's like a page loader since that all the loaded templates are static HTML pages. I want to improve it if is it possible. Here is the code.
on the main index of the project I have a jQuery code like this:
<script>
$(document).ready(function(){
$('.contents').load('templates/home.php');
$(document).on('click','a',function(e){
e.preventDefault();
$('#nav-modal').modal('hide');
var url = $(this).attr('href');
if(url == 'booking/'){
window.location.href= 'booking/';
} else {
$.ajax({
type: 'GET',
url: 'templates/TemplateController.php'+url,
cache: false,
dataType: 'html',
success: function(response){
$('.contents').empty()
.html(response);
}
});
}
});
});
</script>
on the PHP 'controller' side I have this code who will only call a class to obtain the needed files. The URL passed from AJAX
to the controller is something like this: ?tpl=atemplate
<?php
require_once 'Autoloader.php';
if(isset($_GET['tpl'])){
$tpl = new TemplateLoader;
echo $tpl->render($_GET['tpl']);
}
?>
And then in the simple class, I have only a switch
control that will select what is the requested template to load on the index
<?php
class TemplateLoader{
public function __construct(){
#$this->path = $path;
}
public function render($tpl){
switch($tpl){
case 'home':
echo file_get_contents('home.php');
break;
case 'about':
echo file_get_contents('about.php');
break;
case 'services':
echo file_get_contents('services.php');
break;
case 'contacts':
echo file_get_contents('contacts.php');
break;
case 'prices':
echo file_get_contents('prices.php');
break;
}
}
}
?>
jQuery.ajax()
for your requests, you should consider the benefits of the fetch API. Importantly, fetch works asynchronously and it also won't reject on HTTP error codes. If you do not need to worry about authentication or user sessions, then it may be helpful. \$\endgroup\$