Skip to content

Instantly share code, notes, and snippets.

@rdev5
Last active December 17, 2015 23:09
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 rdev5/5686899 to your computer and use it in GitHub Desktop.
Save rdev5/5686899 to your computer and use it in GitHub Desktop.
Need a simple and effective way to add view partials to your CodeIgniter or PHP application? Try this!
<h2>Contact Us!</h2>
<p>Fill out the form below to contact us.</p>
<?=$Partial->render('_form_contact.php', array('c' => $contact_record))?>
<?php
class MY_Controller extends CI_Controller {
public function _output() {
/*
$use_default_view = FALSE;
if ($this->content_view !== FALSE && empty($this->content_view)) {
$this->content_view = $this->router->class . '/' . $this->router->method;
$use_default_view = TRUE;
}
$view_file = APPPATH . 'views/' . $this->theme . '/' . $this->content_view . EXT;
if (class_exists('Modules')) {
if ($use_default_view) {
$module_view = APPPATH . 'modules/' . $this->router->class . '/views/' . $this->theme . '/' . $this->router->method;
if (!method_exists($this->router->class, $this->router->method)) {
redirect('page_not_found');
}
} else {
$module_view = APPPATH . 'modules/' . $this->router->class . '/views/' . $this->theme . '/' . $this->content_view;
}
$module_file = realpath($module_view . EXT);
if (file_exists($module_file)) {
$view_file = $module_file;
}
}
*/
$Partial = new Partial();
$Partial->data = $this->view_data;
$Partial->path = dirname($view_file);
$this->view_data['Partial'] = $Partial;
/*
$default_layout = $this->config->item('default_layout', 'app');
$yield = file_exists($view_file) ? $this->load->view($this->content_view, $this->view_data, TRUE) : FALSE;
if ($this->layout_view)
echo $this->load->view('layouts/' . $this->layout_view, array('yield' => $yield), TRUE);
elseif ($default_layout != '')
echo $this->load->view('layouts/' . $default_layout, array('yield' => $yield), TRUE);
else
echo $yield;
echo $output;
*/
}
}
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Partial {
public $data = array();
public $path = NULL;
public $var_prefix = '_';
public function __construct() {
}
public function render($file = NULL, $data = array()) {
$data = array_merge($this->data, $data);
$partial = realpath($this->path . '/' . $file);
if(file_exists($partial)) {
extract($data, EXTR_PREFIX_SAME, $this->var_prefix);
$Partial = $this;
include($partial);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment