我从问题开始:
我正在关注ellislab.com News_Section的第二个教程。我也看到其他人在本教程中遇到了一些问题,但我还没有发现同样的问题我有......
我的问题是,当从所有新闻导航到一个(在href上)时,我没有收到任何数据。
此路径将显示db中的所有新闻:
http://ignitertut.se/index.php/news/
在这些路径上(例如),我将获得404:
http://ignitertut.se/index.php/news/view/, http://ignitertut.se/index.php/news/view/Rangers/
但是在这条路径上我会得到一个空页:没有数据,没有包含页眉和页脚模板,头部没有通常自动得到一个标题的标题。
http://ignitertut.se/index.php/news/Ragers/
Rangers是关于Rangers的文章的一个slug,存储在DB中。
型号:
<?php
class News_model extends CI_Model {
public function __construct()
{
//Preloaded db
}
public function get_news($slug = FALSE)
{
if ($slug === FALSE)
{
$query = $this->db->get('news');
return $query->result_array();
}
$query = $this->db->get_where('news', array('slug' => $slug));
return $query->row_array();
}
}
包含所有文章的视图 - &#34; index.php&#34;
<?php foreach ($news as $news_item): ?>
<h2><?php echo $news_item['title'] ?></h2>
<div class="main">
<?php echo $news_item['text'] ?>
</div>
<p><a href="news/<?php echo $news_item['slug'] ?>">View article</a></p>
<?php endforeach ?>
特定文章的视图 - &#34; view.php&#34;
<?php
echo '<h2>'.$news_item['title'].'</h2>';
echo '<p>' .$news_item['text']. '</p>';
控制器
class News extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('news_model');
}
public function index()
{
$data['news'] = $this->news_model->get_news();
$data['title'] = 'News archive';
$this->load->view('templates/header', $data);
$this->load->view('news/index', $data);
$this->load->view('templates/footer');
}
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');
}
}
路线
$route['news/(:any)'] = 'news/view/$1';
$route['news'] = 'news';
$route['(:any)'] = 'pages/view/$1';
$route['default_controller'] = 'pages/view';
我已自动加载数据库并设置:
$config['base_url'] = 'http://ignitertut.se/';
(在本地运行)
答案 0 :(得分:0)
你称之为slug的词是url参数。在codeigniter中有一种获取url参数的方法。
为了使您现有的代码更改控制器功能以查看此
public function view()
{
$slug = $this->uri->segment(2);
$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');
}
请参阅此网址以获取更多详细信息 http://ellislab.com/codeigniter/user-guide/libraries/uri.html