开发者

How do you create relative links in CodeIgniter?

Example I have the following code in Controller:

class Main extends CI_Controller {

    public function index()
    {
        $this->load->view('main_view');
    }

    public function create ()
    {
        $this->load->view('create_view');

    }
开发者_StackOverflow社区}

If I want to create a relative link to create, how do I accomplish that? The following link in view doesn't always work. What is apporpiate way to create relative links in CodeIngiter?

<a href="create"> Create </a>


<a href="<?= site_url('/main/create'); ?>"> Create </a>

or simply:

<?= anchor('/main/create', 'Create'); ?>

Make sure you have loaded the URL Helper.


You don't have to do anything special or load any helpers, just keep in mind that paths will be relative to the url and not the filesystem or controller.

Assuming your installation is in the root directory of your domain, let's say your current URL is http://localhost/class/method/var:

<a href="/main/create">Will work from anywhere</a>
<a href="create">Will go to http://localhost/class/method/var/create</a>
<a href="../create">Will go to http://localhost/class/method/create</a>

Relative paths are not your friend in Codeigniter, you are better off sticking with full urls (typically using the helper functions like base_url() and site_url()), or to use the forward slash (relative from root). People have mentioned using the <base> html tag, but I don't personally recommend it. You are going to have some very wacky urls if you use ../../relative paths when you get deeper into the url segments. Example:

If you are here: http://localhost/controller/method/var1/var2/var3

A link might look like this: <a href="../../../../controller2/method/othervar"></a>

Probably not what you want, but it's an option you may choose. I recommend using one of the other two.


Just to point another alternative, if you dont like the idea of writing a php fragment in each href, and if the other approaches don't satisfy you. You can use put a common <BASE > tag in your html header (for example that points to the root of your application), and then remember that every relative url in your pages will be with respect with that url.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜