Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is_home() function in Codeigniter

As I know the Wordpress has is_home() function to determine home page.
In YII i use solution like this Yii check if homepage

In CI, templates actually, i faced many times with necessity of it. For example, adding some css classes in tag <body>.

All what i found http://ellislab.com/forums/viewthread/194637/#916899
Can anybody help me or write own solution?

Thank in advance

like image 239
Andrei Zhamoida Avatar asked May 06 '13 16:05

Andrei Zhamoida


3 Answers

I just wanted to add my answer here as the other method doesn't work with my heavily modified version of CI.

This snippet is what I use to detect if we are on the homepage

if (!$this->uri->segment(1)) {
    // We are on the homepage
}
like image 180
Adam Avatar answered Sep 22 '22 13:09

Adam


You can use $this->router->fetch_class() to get the current controller and $this->router->fetch_method() to get the method too if needed.

So similar to the Yii example you linked to, you could do something like

$is_home = $this->router->fetch_class() === 'name_of_home_controller' ? true : false;

Or to match method too

$is_home = ($this->router->fetch_class() === 'name_of_home_controller' && $this->router->fetch_method() === 'name_of_home_method') ? true : false;

This way even if the page url is http://yoursite.com/ (assuming the home controller+method is the default), http://yoursite.com/home_controller/, http://yoursite.com/something/that/routes/to/home/controller/, etc, as long as it's calling that controller, it'll set $is_home to true.

Edit: Also you can use ($this->router->fetch_class() === $this->router->default_controller) if you don't want to explicitly state the home controller and it's set to the default controller.

Update for CI v3:
$this->router->fetch_class() and $this->router->fetch_method() were deprecated in CI v3. Use $this->router->class and $this->router->method instead.

like image 43
Samutz Avatar answered Sep 25 '22 13:09

Samutz


if($this->uri->uri_string() == ''){ 
echo"You are on homepage"; 
}
like image 42
nixis Avatar answered Sep 23 '22 13:09

nixis