Codeigniter网址,加倍细分,如:新闻/新闻/

时间:2012-03-31 14:18:42

标签: php codeigniter url-routing

我已经完成了CI文档中包含的众所周知的'新闻'插曲。有时候我的链接字符串会出现双重“新闻/”段,如下所示:'/ codeig / news / news / entry'有时在重新加载页面之后一切正常。我应该提到我已经摆脱了'index.php'片段之后的另一个流行教程。我的代码出了什么问题?

这是我的路线:

$route['news/create'] = 'news/create'; 
$route['news/update/(:any)'] = 'news/update/$1';
$route['news/delete/(:any)'] = 'news/delete/$1';
$route['news/(:any)'] = 'news/view/$1';
$route['news'] = 'news';
$route['welcome'] = 'welcome';

$route['auth/(:any)'] = 'auth/$1';
$route['auth'] = 'auth';
$route['activate/:num/:any'] = "/auth/activate/$1/$2";
$route['reset_password/:num/:any'] = "/auth/reset_password/$1/$2";

$route['(:any)'] = 'pages/view/$1';
$route['default_controller'] = 'news';

views / news / index.php文件:

<?php foreach ($news as $news_item): ?>

<h2><?php echo $news_item['title'] ?></h2>
<div id="main">
    <?php echo $news_item['text'] ?>
</div>
<p><a href="news/<?php echo $news_item['slug'] ?>">View article</a></p>

<?php endforeach ?>

查看方法(新闻控制器)

public function view($slug)
{
$data['news_item'] = $this->news_model->get_news($slug);

if (empty($data['news_item']))
{
    show_404();
}

$data['title'] = $data['news_item']['title'];

$this->load->view('templates/header', $data);
$this->load->view('news/view', $data);
$this->load->view('templates/footer');
}

2 个答案:

答案 0 :(得分:8)

在HTML中,如果当前的URL是这样的:

  

http://example.com/news/

你有这样的链接:

<a href="news/article-slug">Link</a>

点击该链接后,您的网址将最终成为:

  

http://example.com/news/news/article-slug

如果您再次点击它,您将拥有:

  

http://example.com/news/news/article-slug/news/article-slug

注意:这不完全正确,路径的相对性取决于当前网址和/或链接中是否有尾部斜杠/。< / p>

href="news/something"是相对于当前页面的相对网址。您想使用绝对或根网址:

<a href="http://example.com/mysite/news/article-slug">Link</a>
<a href="/news/article-slug">Link</a>

使用以下任何Codeigniter功能使绝对URL更容易:

  • anchor()(为您制作完整链接)
  • site_url()(返回您的绝对基本网址)
  • base_url()(与上述相同)
<?php echo anchor('news/'.$news_item['slug'], 'Link Text'); ?>
<a href="<?php echo base_url('news/'.$news_item['slug']); ?>">Link Text</a>

所以只是为了澄清一下,这与您的路由无关 - 这纯粹是HTML中相对链接的问题。

答案 1 :(得分:2)

不太详细的解释:

在'application / views / news / index.php'文件中

之前(导致/ news / news / in URL):

<p><a href="news/<?php echo $news_item['slug'] ?>">View article</a></p>

之后(已修复):

<p><a href="<?php echo $news_item['slug'] ?>">View article</a></p>

news/包含在$news_item['slug']中,因此不需要在HTML中。