Search code examples
phpcodeignitercodeigniter-2

Using Page $data variables in template


Is there a way to use page $data variables in the template it's loaded in?

For instance - if I have a template that has a head like this:

<!DOCTYPE html>
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
    <head>
  <title><?php echo $data['title']; ?> | ACME, Inc.</title>
</head>

My view is pages/home and the controller looks something like this:

 public function index($data) {


$data = array();
            $data['title'] = 'Home';

        $this->load->view('pages/home', $data);
}

How do I get a parent template or sibling view to take on the page's variables?


Solution

  • I usually use the code below for meta data in page

    In controller:

     $page = new stdClass();
            $page->title = "Your Page Title";
            $page->desc = "Your page description";
            $page->key = "keword1,keyword2,keyword3";
            $page ->author = "Alex";
    
     $data['page'] = $page;
     $this->load->view('pages/home', $data);
    

    In View:

    <title><?php
    if(isset($page->title)){
    echo $page->title;
    }
    ?></title>
    <meta name="description" content="<?php
    if(isset($page->desc)){
    echo $page->desc;
    }
    ?>"/>
    <meta name="keywords" content="<?php
    if(isset($page->key)){
    echo $page->key;
    }
    ?>"/>
    <meta name="author" content="<?php
    if(isset($page->author)){
    echo $page->author;
    }
    ?>"/>
    content="<?php
    if(isset($page->desc)){
    echo $page->desc;
    }
    ?>"/>
    

    This is safe for not conflicting variable and easy to use.