简体   繁体   English

CodeIgniter中的当前URI段

[英]Current URI Segment in CodeIgniter

What would be the best way to check for the current URI segment in a CodeIgniter view? 在CodeIgniter视图中检查当前URI段的最佳方法是什么? What I am trying to do is use the current URI segment [ie $this->uri->segment(1)] in order to highlight the current page on the navigation bar. 我想要做的是使用当前的URI段[即$ this-> uri-> segment(1)],以突出显示导航栏上的当前页面。

The best that I have figured out is to do 我想到的最好的事情就是去做

$data['current_uri'] = $this->uri->segment(1);
$this->load->view('header', $data);

in each of my controllers and then in the header.php file, I check the $current_uri variable to determine which part of the navigation should be highlighted. 在我的每个控制器中,然后在header.php文件中,我检查$ current_uri变量以确定应该突出显示导航的哪个部分。 As you know, this is a very tedious way of doing it, but I'm at a loss of a better way to do this. 如你所知,这是一种非常繁琐的方式,但我却失去了一种更好的方法。

It may even be possible to extend the default Controller class to pass the current URI segment, but I'm not sure if this would work, or even how to go about doing it. 甚至可以扩展默认的Controller类来传递当前的URI段,但我不确定这是否可行,甚至不知道如何去做。

I myself use an extra function similar to anchor(). 我自己使用类似于anchor()的额外函数。 I call it active_anchor(), and it takes all the same parameters plus another (the uri). 我将其称为active_anchor(),它采用所有相同的参数加上另一个(uri)。 The function then adds the class 'active' if the uri string passed matches the active_anchor() url paramter. 如果传递的uri字符串与active_anchor()url参数匹配,则函数会将类添加为“active”。

Then the function returns using the anchor function (all that the function did was determine if the link needed the class 'active' or not. 然后函数使用锚函数返回(函数所做的就是确定链接是否需要类'活动'。

EDIT: 编辑:

I just put this code in a file called 'MY_url_helper.php'. 我把这段代码放在一个名为'MY_url_helper.php'的文件中。 That way, when the url helper is loaded (I actually auto load that one since pretty much all of my views use it anyway.) This is just some quick code too, pretty sure it would work. 这样,当加载url帮助器时(我实际上是自动加载那个,因为我的几乎所有视图都使用它。)这只是一些快速代码,非常确定它会起作用。 Basically it takes the same arguments as the anchor() function, but also the $key variable. 基本上它采用与anchor()函数相同的参数,但也使用$ key变量。 It appends a class of "active" to the anchor tag if the key and url match. 如果key和url匹配,它会向anchor标记添加一个“active”类。

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if ( ! function_exists('active_anchor'))
{
    function active_anchor($url = NULL, $title = NULL, $key = NULL, $params = array())
    {
        if ($url && $key)
        {
            if($key == $url)
            {
                if (array_key_exists ('class' , $params))
                {
                    $params['class'] .= ' active';
                }
                else
                {
                    $params['class'] = 'active';
                }
            }
        }
        return anchor($url, $title, $params);
    }
}

this simple way and running well for me.. 这种简单的方式,对我运行良好..

<li class="<?=($this->uri->segment(2)==='test')?'current-menu-item':''?>"><?php echo     anchor ('home/index','HOME'); ?></li>

<li class="<?=($this->uri->segment(2)==='blog')?'current-menu-item':''?>"><?php echo     anchor ('home/blog','BLOG'); ?></li>
<li class="<?=($this->uri->segment(2)==='bla..bla')?'current-menu-item':''?>"><?php     echo anchor ('home/blog','bla..bla'); ?></li>

uri_segment(2) that mean function in ur controller. uri_segment(2)表示你的控制器中的函数。

but have a weakness, i have trouble if i put view in index controller, so im not use function index ( toruble in uri segment, make 2 current page in same time... read this http://ellislab.com/codeigniter/user-guide/libraries/uri.html 但是有一个弱点,如果我把视图放在索引控制器中我会遇到麻烦,所以我不使用函数索引(uri段中的toruble,同时制作2个当前页面...阅读http://ellislab.com/codeigniter/用户导/库/ uri.html

Simple way to check the uri segment in view, 

Add some code if matches found.
 <li class="<?php echo (strcmp($this->uri->segment(2),'test')==0)?'active':''; ?>"><li>
 <li class="<?php echo (strcmp($this->uri->segment(2),'test1')==0)?'active':''; ?>"><li>
 <li class="<?php echo (strcmp($this->uri->segment(2),'test2')==0)?'active':''; ?>"><li>

I also had the same problem when I was building a customer website in Cakephp, passing those strings for every menu item from controller to view, then checking again in view for implementing the highlighting to tedious to say the least. 当我在Cakephp中构建一个客户网站时,我也遇到了同样的问题,将每个菜单项的字符串从控制器传递到视图,然后再次检查以实现突出显示,至少可以说乏味。

For some of my projects now, I have been implementing the same by storing the page information for each of the navigation menu pages in database, things like page name, url, title, position in navigation menu etc. 对于我现在的一些项目,我通过在数据库中存储每个导航菜单页面的页面信息来实现相同的功能,例如页面名称,URL,标题,导航菜单中的位置等。

Then at the start of controller, I store all this data in an array say $pageinfo . 然后在控制器的开始,我将所有这些数据存储在一个数组中,如$pageinfo

I handle the navigation functionality via a single controller that checks the URI segment and loads the content based on that. 我通过单个控制器处理导航功能,该控制器检查URI段并基于此加载内容。

The highlighting part is left to an if statement when generating the view, where I compare each page name to the information I dumped in $pageinfo . 生成视图时,突出显示部分留给if语句,我将每个页面名称与我在$pageinfo转储的信息进行比较。

Something like this... 像这样......

foreach ($navi_menu as $links) {
    if ( $links['title'] == $pageinfo['title'] ) {
      // Highlight here
    }
    else {
      // No highlight
    }
}

This way I don't need to pass the string constants (uri segments in your case) to the view. 这样我就不需要将字符串常量(在您的情况下为uri段)传递给视图。 This CMS-kinda-approach allows me to flexible in adding further items to my menu, without adding more code. 这种CMS-kinda-approach允许我灵活地在菜单中添加更多项目,而无需添加更多代码。

I remember getting this from a codeigniter wiki, can't find the link to it right now. 我记得从codeigniter维基得到这个,现在找不到它的链接。

In every CodeIgniter project I gather some basic information about the request in MY_Controller. 在每个CodeIgniter项目中,我都会在MY_Controller中收集有关请求的一些基本信息。

I extend the core controller and put in some initialization logic that needs to happen on every page. 我扩展了核心控制器并放入了需要在每个页面上发生的一些初始化逻辑。 This includes getting the information about the controller and method, which is passed to the view. 这包括获取有关控制器和方法的信息,该信息将传递给视图。 As a short example: 举个简短​​的例子:

class MY_Controller extends CI_Controller
{
    protected $_response_type = 'html';
    protected $_secure;
    protected $_dir;
    protected $_controller;
    protected $_method;
    protected $_template;
    protected $_view;
    protected $_user;

    public function __construct()
    {
        parent::__construct();

        // Gather info about the request
        $this->_secure = ! empty($_SERVER['HTTPS']);
        $this->_dir = $this->router->fetch_directory();
        $this->_controller = $this->router->fetch_class();
        $this->_method = $this->router->fetch_method();

        // set the default template and view
        $this->_template = 'default';
        $this->_view = $this->_dir . $this->_controller . '/' . $this->_method;
    }

    /**
     * Performs operations right before data is displayed.
     *
     * @access public
     * @return void
     */
    public function _pre_display()
    {
        if ($this->_response_type === 'html') {
            $this->load->vars(array(
                'user' => $this->_user
            ));
        }
        elseif ($this->_response_type === 'json') {
            $this->_template = 'json';
            $this->_view = NULL;
        }
        else {
            show_error('Invalid response type.');
        }

        $this->load->vars(array(
            'is_secure' => $this->_secure,
            'controller' => $this->_controller,
            'method' => $this->_method
        ));
    }
}

Now in a view such as the navigation you can use that information like this: 现在在导航等视图中,您可以使用以下信息:

<a href="<?php echo site_url('products') ?>"<?php echo ($controller === 'products') ? ' class="selected"' : ''; ?>>Products</a>

I like it because with routes or rewrites you may access controllers and methods from different URLs. 我喜欢它,因为通过路由或重写,您可以从不同的URL访问控制器和方法。 This way you set whether the link is active based on the controller/method that is serving up the content and not based on the URL. 这样,您可以根据提供内容而不是基于URL的控制器/方法来设置链接是否处于活动状态。

Also, this information can be reused within your controllers or views for any reason and you are not continually asking the router or uri to calculate the information (which not only is inefficient, but is cumbersome to write over and over). 此外,这些信息可以出于任何原因在您的控制器或视图中重复使用,并且您不会不断要求路由器或uri计算信息(这不仅效率低,而且反复编写也很麻烦)。

I'll probably get flamed for suggesting a client-side approach, but this is something I've used in the past to mark the current page as highlighted: 我可能会因为提出客户端方法而受到抨击,但这是我过去用来将当前页面标记为突出显示的内容:

var path = location.pathname.substring(1);
if ( path )
 $('#navigation a[href$="' + path + '"]').parents('li').attr('class', 'current');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM