php CodeIgniter 中的当前 URI 段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3673514/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:39:01  来源:igfitidea点击:

Current URI Segment in CodeIgniter

phpcodeigniter

提问by Jared

What would be the best way to check for the current URI segment in a CodeIgniter view? What I am trying to do is use the current URI segment [i.e. $this->uri->segment(1)] in order to highlight the current page on the navigation bar.

在 CodeIgniter 视图中检查当前 URI 段的最佳方法是什么?我想要做的是使用当前的 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. 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.

在我的每个控制器和 header.php 文件中,我检查 $current_uri 变量以确定应该突出显示导航的哪一部分。如您所知,这是一种非常乏味的方法,但我不知道有更好的方法来做到这一点。

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 段,但我不确定这是否可行,甚至不确定如何去做。

采纳答案by Matthew

I myself use an extra function similar to anchor(). I call it active_anchor(), and it takes all the same parameters plus another (the uri). The function then adds the class 'active' if the uri string passed matches the active_anchor() url paramter.

我自己使用了一个类似于 anchor() 的额外函数。我称之为active_anchor(),它需要所有相同的参数加上另一个(uri)。如果传递的 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'. 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. Basically it takes the same arguments as the anchor() function, but also the $key variable. It appends a class of "active" to the anchor tag if the key and url match.

我只是将此代码放在名为“MY_url_helper.php”的文件中。这样,当 url 助手被加载时(我实际上自动加载了那个,因为我几乎所有的视图都使用它。)这也只是一些快速代码,很确定它会工作。基本上它采用与 anchor() 函数相同的参数,但还有 $key 变量。如果键和 url 匹配,它会将一类“活动”附加到锚标记。

<?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);
    }
}

回答by vikmalhotra

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.

然后在控制器开始时,我将所有这些数据存储在一个数组中 say $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. This CMS-kinda-approach allows me to flexible in adding further items to my menu, without adding more code.

这样我就不需要将字符串常量(在您的情况下为 uri 段)传递给视图。这种 CMS-kinda-approach 允许我灵活地将更多项目添加到我的菜单中,而无需添加更多代码。

I remember getting this from a codeigniter wiki, can't find the link to it right now.

我记得是从 codeigniter wiki 获得的,现在找不到它的链接。

回答by Prabu Karana

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

回答by prash.patil

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>

回答by None

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. 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 访问控制器和方法。通过这种方式,您可以根据提供内容的控制器/方法而不是基于 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 计算信息(这不仅效率低下,而且一遍又一遍地写起来很麻烦)。

回答by someoneinomaha

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');