更改页面标题 - 确定当前页面的内容

时间:2013-07-03 15:39:45

标签: php codeigniter

我正在开发codeigniter,我想知道什么是动态更改标题的最佳方式。例如。如果您在主页,单个帖子页面,类别页面等,标题将会改变。

我能想到的唯一解决方案是制作单独的功能并将当前URL(来自地址栏)与单个帖子页面,类别页面,主页的结构进行比较

这样的事情:

public function current_title() { 
   if($this->uri->segment(2) == 'post') { 
      // will return post title 
    }

   if($this->uri->segment(2) == 'category') { 
      // will return archive title 
    }

    if(current_url() == base_url()) { 
      // this is home page 
    }

如果有人之前使用过这个,那么任何建议都会受到高度赞赏

4 个答案:

答案 0 :(得分:2)

我不会使用uri,而是使用控制器和操作名称以及语言类:

public function current_title() 
{
    $this->lang->load('titles.php', 'en');

    return $this->lang->line(
        $this->router->fetch_class().'.'.$this->router->fetch_method()
    );
}

您的翻译会有MyClass.myMethod之类的密钥。只需在titles.php文件中添加标题:

即可
$lang['MyClass.myMethod'] = "The title";
$lang['MyOtherClass.myOtherMethod'] = "The other title";

了解有关翻译的更多信息:
http://ellislab.com/codeigniter/user-guide/libraries/language.html
http://ellislab.com/codeigniter/user-guide/helpers/language_helper.html

答案 1 :(得分:2)

//在控制器中你应该这样做:

 class Home extends your_Controller {
      public function __construct() {
          parent:: __construct();
         }
       function index()
       { 
       $this->data['pageTitle'] = 'Your page title';
        $data['main_content'] = 'home';
        $this->load->view('includefolder/viewname', $data);
       }
    }

答案 2 :(得分:0)

我就是这样做的:

$PHPFile = basename($_SERVER['PHP_SELF'],'.php');
switch ($PHPFile) {
    case 'index': $PageTitle = 'Home'; break;
    case 'products': $PageTitle = 'Products'; break;
    case 'services': $PageTitle = 'Services'; break;
}

您可以使用字符串搜索或任何需要的内容。我使用这种方法,因为我将页面的标题作为库中的函数。

答案 3 :(得分:0)

因为我们为每个视图都有一个控制器功能,所以你可以从url轻松获取函数名称

$this -> router -> fetch_module();

所以你可以使用它。