I have a header.php I'm loading in my controllers for every page. However I want to have dynamic titles for each page. My idea was to pass a $title variable into the view as I'm loading it:
//Home Controller
function index()
{
$data['title'] = "Dynamic Title";
$this->load->view('header', $data);
$this->load->view('layouts/home');
$this->load->view('footer');
}
and then check for the $title variable in my header.php
<title>
<?php if ($title)
{
echo $title;
}
else
{
echo 'Default Title';
}
endif; ?>
</title>
However this doesn't work and I get a blank page. I think it is my syntax for the header.php but I can't figure out why.
if
SyntaxYour syntax on the if-statement
is a bit off. You can use either:
if (condition) {
// do a
} else {
// do b
}
Or
if (condition) :
// do a
else :
// do b
endif;
You seem to have transposed the ending of the latter onto the former.
Once you've made that change, your title can be printed as easily as:
<title><?php echo isset($title) ? $title : 'Default Title' ; ?></title>
Another method of loading views is to work with a single template file:
$data['title'] = 'Foo Bar';
$data['content'] = 'indexPage';
$this->load->view('template', $data);
This loads the template.php
file as your view. Within this file you load your subsequent parts:
<?php $this->load->view("_header"); ?>
<?php $this->load->view($content); ?>
<?php $this->load->view("_footer"); ?>
By no means is this necessary, but it may help you maintain brevity in your controller.
Well I would try doing a var dump of $title in the view, just to see if it's getting passed at all.
Also, you don't need "endif;" since you're ending the if statement with the last curly brace.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With