CodeIgniter Forums
Header and footer - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived General Discussion (https://forum.codeigniter.com/forumdisplay.php?fid=21)
+--- Thread: Header and footer (/showthread.php?tid=2059)



Header and footer - El Forum - 07-13-2007

[eluser]Anderson Mello[/eluser]
Hi guys,

I'm new in CI and I was thinking using one view with header information and another with footer. Then, with a custom method like $this->load->content('view_name'), both are included automatically. This way, I could insert all the metas, CSS and scripts tags as needed, avoiding editing too many views or including the header and footer view on each file.

Maybe the way I'm trying isn't the right one or maybe it can't be in that way... Smile

Regards,
Anderson Mello


Header and footer - El Forum - 07-17-2007

[eluser]Phil Sturgeon[/eluser]
This is what most CI developers do. I myself made a nice little library which extends the parser but there are easier methods.

Make a library with a few functions, title() can set the page title, wrap(true/false) to say if you want the headers/footers and create() which has the same options as load->view(). Give it filename, data and return or output.

Then when you have a snazzy little library you can add crazy things like dynamic title generation (works it out from class and method names) and add blocks, default variables, user data, etc. Will save you lots of time to do this, give me a shout if you want mine.


Header and footer - El Forum - 07-18-2007

[eluser]Phil Sturgeon[/eluser]
As per requested in your PM:

Code:
<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter Template Class
*
* Helps create pages easier with more options than load->view()
*
* @package        CodeIgniter
* @subpackage    Libraries
* @category    Libraries
* @author        Philip Sturgeon
* @link        
*/
class Template {

    var $CI;

    var $filename = '';
    var $directory = '';
    var $title = '';
    var $data = array();
    
    // Set default blocks
    var $blocks = array('navigation', 'to-do');
    
    var $header = 'header.php';
    var $footer = 'footer.php';

    var $wrap = true;

    /**
     * Constructor - Calls the CI instance and sets a debug message
     *
     * The constructor can be passed an array of config values
     */    
    function Template()
    {        
        $this->CI =& get_instance();
        log_message('debug', "Template Class Initialized");
        
        if($this->directory == '' && $this->CI->uri->router->directory != ''):
            $this->directory = $this->CI->uri->router->directory;
        endif;
    }
    
    // --------------------------------------------------------------------
    
    /**
     * Set the mode of the creation
     *
     * @access    public
     * @param    string
    
     * @return    void
     */    
    function create($filename = '', $data = array(), $return = false)
    {
        $this->CI =& get_instance();
        
        if($filename != '') $this->filename = $filename;
        if($data != array()) $this->data = $data;
        
        // Work out the basics the template will need
        $this->_set_defaults();
        
        // Want header and footer file included, or just the main file?
        if($this->wrap === true):
            
            $output  = $this->CI->load->view($this->directory.$this->header, $this->data, true);
            $output .= $this->CI->load->view($this->directory.$this->filename, $this->data, true);
            $output .= $this->CI->load->view($this->directory.$this->footer, $this->data, true);
        else:
            $output = $this->CI->load->view($this->directory.$this->filename, $this->data, true);
        endif;
        
        // Want it returned or output to browser?
        if($return):
            return $output;
        else:
            // Send it to output
            $this->CI->output->set_output($output);
        endif;
    }
    
        
    /**
     * Set the title of the page
     *
     * @access    public
     * @param    string
     * @return    void
     */    
    
    function title($title = '')
    {
        if($title != '') $this->title = $title;
    }
    
    function directory($directory = '')
    {
        if($directory != '') $this->directory = $directory;
    }
    
    /**
     * Should we include headers and footers?
     *
     * @access    public
     * @param    string
     * @return    void
     */    
    function wrap($wrap = true)
    {
        $this->wrap = $wrap;
    }
    
    /**
     *  Set some basic variables to be available to all pages
     *
     * @access    public
     * @param    string
     * @return    void
     */    
    function _set_defaults()
    {
    
        $this->CI =& get_instance();
    
        $this->CI->load->library('session');        
        $this->CI->load->helper('inflector');
        
        // Replace all underscores with spaces, then capitalise first letters of words
        $defaultTitle = humanize($this->CI->uri->router->class .' > '.$this->CI->uri->router->method);
        
        // Set the basic defaults
        $this->data['pageTitle'] = ($this->title) ? $this->title : $defaultTitle;        
        
        if($this->blocks != array()):
            $this->data['blocks'] = $this->_build_blocks();
        endif;
        
            
        $this->CI->load->library('permission');

        if(is_object($this->CI->permission)):
            $user_result = $this->CI->permission->check();
            
            $this->data['if_logged_in'] = ($user_result) ? array(array()) : array();
            $this->data['if_not_logged_in'] = (!$user_result) ? array(array()) : array();
            
            $manager_result = $this->CI->permission->check('manager');
            
            $this->data['if_manager'] = ($manager_result) ? array(array()) : array();
            $this->data['if_not_manager'] = (!$manager_result) ? array(array()) : array();
        endif;
            
    }
    
    /**
     * Set the mode of the creation
     *
     * @access    public
     * @param    array
     * @return    array
     */    
    
    function _build_blocks()
    {
        
        $blockArray = array();
        
        foreach($this->blocks as $blockName):

            $block_data = array();
            include(APPPATH.'views/blocks/'.$blockName.'_code.php');
            
            $this->data = array_merge($this->data, $block_data);
            
            $blockContent = $this->CI->load->view('blocks/'.$blockName, $this->data, true);
            $blockArray[] = array('name' => $blockName, 'content' => $blockContent);
        endforeach;

        return $blockArray;
    
    }
    
}
// END Template class
?>

The blocks system is VERY un-finished but atm all you need is a view file in the /blocks/name.php and a file /blocks/name_code.php. This PHP needs to create a variable called $block_data which will be called by this function.

Its far from perfect but if you cant be bothered with the blocks, just make the $this->blocks array empty and it shouldnt do anything.

Example:

Code:
$this->template->title('Hello!');
$this->template->create('pagename', $data);

Also, if your controller is in a sub directory, it will automatically look for a header and footer file in the sub directory. Guess I should clean this lib up and release it sometime.


Header and footer - El Forum - 07-18-2007

[eluser]Anderson Mello[/eluser]
Hello thepyromaniac, thanks for the replies Wink
I was trying some things and I've found me on a maze, 'cause I din't knew about the third parameter of the view() method. So, I was trying to start my header and footer template with something like:

Code:
function mostra($view, $data) {
    $this->CI->load->view('header_view', $data);
    $this->CI->load->view($view);
    $this->CI->load->view('footer_view');
}

But doing this, only the footer was displayed. If I comment the footer line, the main ($view var file) comes. I could solved it with buffering but that doesn't sounded a good idea for me.

I'll study your library (that have teach me a lot already Smile) and post implements that could be made.
Thank you again!

Regards,
Anderson Mello


Header and footer - El Forum - 07-19-2007

[eluser]BravoAlpha[/eluser]
I'm new to CodeIgniter... I'm using something like this in my current project:

Example of a controller method:
Code:
function index()
{
// The rest of the controller...

$data['html_title'] = 'Example';
$data['html_views'] = array('welcome/index');
$this->load->vars($data);
$this->load->view('container');
}

container.php
Code:
<!-- Example -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title><?php echo htmlspecialchars($html_title); ?></title>
<head>
<body>

<?php

foreach ($html_views as $html_view)
{
$this->load->view($html_view);
}

?>

</body>



Header and footer - El Forum - 07-20-2007

[eluser]Anderson Mello[/eluser]
BravoAlpha, that's pretty good too Wink
Some friend of mine uses something like that for specify the .js and .css files to load with the view.
I'm adapting that in a library using two fixed files (header and footer). Like this:

header_view.php
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
&lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="pt-br" lang="pt-br"&gt;
&lt;head&gt;
&lt;title&gt;&lt;?php echo $titulo;?&gt;&lt;/title&gt;
&lt;meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1" /&gt;
&lt;meta name="language" content="pt-br" /&gt;
&lt;meta name="resource-type" content="document" /&gt;
&lt;meta name="classification" content="Internet" /&gt;
&lt;meta name="rating" content="General" /&gt;
&lt;meta name="robots" content="no-follow" /&gt;
&lt;meta name="author" content="Anderson Mello" /&gt;
&lt;meta name="subject" content="[email protected]" /&gt;
&lt;meta http-equiv="imagetoolbar" content="no" /&gt;

&lt;?php
/**
* Include .js files
*/
if (isset($js) && is_array($js)) {
echo "\n";
for($i = 0; $i < count($js); $i++) {
  echo " \n";//here in the echo goes the js script tag... the forum doesn't support it
}
}

/**
* Include .css files
*/
if (isset($css) && is_array($css)) {
echo "\n";
for($i = 0; $i < count($css); $i++) {
  //echo "\timport url(\"/". PATH ."css/". $css[$i] .".css\");\n";
  echo " &lt;link rel=\"stylesheet\" type=\"text/css\" href=\"css/" . $css[$i] . ".css\"&gt;\n";
}
}
?&gt;
&lt;/head&gt;
&lt;body&gt;

footer_view.php
Code:
<hr>
<p><em>{elapsed_time} secs</em></p>
&lt;/body&gt;
&lt;/html&gt;



Header and footer - El Forum - 07-20-2007

[eluser]wemago[/eluser]
why dont you do something like this

in controller
Code:
function exemplo()
{
   $data['pagina'] = 'exemplo';
   $this->load->view('loader', $data);
}

in views - loader.php
Code:
&lt;?php
   $this->load->view('comum/header');
   $this->load->view('conteudo/'.$pagina);
   $this->load->view('comum/footer');
?&gt;

You will have two folders in view, a common for the stuff you want to repeat and a content folder for the "dynamic" stuff.

I think this is the most easy way of doing this without building new librarys or extending the ci parser.
There's a old post here available about this, cant remember the link.


Header and footer - El Forum - 07-20-2007

[eluser]sophistry[/eluser]
An item in the FAQ addresses how to do header, main, footer style layouts/templates/view in CI.
CodeIgniter FAQ on Wiki
If you find any other resources, please link them to this FAQ so that others may benefit. :-)


Header and footer - El Forum - 07-23-2007

[eluser]Anderson Mello[/eluser]
wemago, this a simple and easy way for sure Wink
I'll use something like that in some cases, but I'm still trying to make a library or something to customize things like the title of the page, styles and javascript stuff. Thanks for the reply!

sophistry, I'll read and study the library on this link. Seems really a interesting one. I'll post if I've some sugestions too. Thanks! :-)

Regards,
Anderson Mello


Header and footer - El Forum - 07-27-2007

[eluser]IanJ[/eluser]
After playing with CI for a couple of hours, I came up with this little solution I added to the loader.
Code:
/*------------------------------------------------------------
    |
    | viewLayout($template, $data = array(), $layoutData = array(), $layout = 'default')
    |
    | Renders output with a layout, rather than using
    | two statements in the code, this will do the same
    | in one. Layouts are stored in the views/layouts
    | directory.
    |
    | Required:
    | $template -     the tempalte to render as normally would
    |                with $this->load->view('template');
    |
    | Optional:
    | $data -        the data to be rendered with the template
    |
    | $layoutData -    data to be included in the layout, DO NOT
    |                USE content_for_layout in the $layoutData
    |                array
    |
    | $template -     the template to render, defaults to default
    |
    +------------------------------------------------------------*/
    function layout($template, $data = array(), $layoutData = array(), $layout = 'default'){
        
        $layoutData['content_for_layout'] = $this->_ci_load(array('view' => $template, 'vars' => $this->_ci_object_to_array($data), 'return' => true));

        $this->_ci_load(array('view' => "layouts/$layout", 'vars' => $this->_ci_object_to_array($layoutData), 'return' => false));
        
    }
It treats the layout as just another view so you can pass a normal array of variables in and parse them in the layout just like a normal view. Just make sure to add
Code:
&lt;?php echo $content_for_layout; ?&gt;
to your layout files.

Ian