[eluser]dailygrind[/eluser]
I'd like to share my code for automatic views (it's a bit rails-like) and get suggestions.
I have an application view: "./views/layout/application.php" just like the one below
Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Your title</title>
<?= isset($head_code) ? $head_code : "" ?>
</head>
<body>
<?= isset($contents) ? $contents : "" ?>
</div>
</body>
</html>
and a main controller:
Code:
<?
class APP_Controller extends Controller {
protected $vars;
protected $has_layout = true;
public $language;
function __construct() {
parent::__construct();
// LANGUAGE : /en/class/method/
$this->language = ($this->uri->segment(1)=="it" || $this->uri->segment(1)=="en") ? $this->uri->segment(1) : "it";
$this->lang->load($this->language,$this->language);
// DEFAULT VIEWS CONTENTS
$this->vars["contents"] = "";
}
function _output() {
if($this->has_layout) {
$view = $this->router->class."/".$this->router->method;
$standard_view_exists = read_file("./application/views/".$view.".php");
$local_view_exists = read_file("./application/views/".$view."_".$this->language.".php");
if($this->vars["contents"]=="" && ($standard_view_exists || $local_view_exists)) {
// VIEW
$load_view = $local_view_exists ? $view."_".$this->language : $view;
$this->vars["contents"] = $this->load->view($load_view,$this->vars,true);
// INIT VIEW
$init_view_exists = read_file("./application/views/".$view."_init.php");
if($init_view_exists) $this->vars["head_code"] = $this->load->view($view."_init", $this->vars, true);
}
$this->load->view("layout/application",$this->vars);
echo $this->output->get_output();
}
}
}
This way you can have a default application view with automatic views:
en/home/method => will load ./views/home/method.php
en/home/method => will load ./views/home/method_en.php (if exists)
If you want to use other layouts other than defaults you can just set
Code:
$this->has_layout = false;
in your method/constructor and use whatever you like.
It will also load into "head_code" any view called with the "_init.php" extension if they exist. I don't know if this is a good idea, but I was just looking for a way to emulate Rails "content_for" in views.
Does this make sense to you? How do you structure your application views?
Ciao!