我会将一个变量传递给来自数据库的Phil Sturgeon模板库中的title函数参数。
我有这些文件:
控制器
class Blog extends CI_Controller {
public function post($id)
{
$this->load->model('blog_model');
$data['post'] = $this->blog_model->get_post($id);
$data['comments'] = $this->blog_model->get_post_comments($id);
if($data['post'])
{
$this->template
->title(?????????) <- HERE IS THE PROBLEM!
->build('blog/post', $data);
}
else
{
$this->flash_message->error('Post doesn't exist');
redirect('blog');
}
}
}
模型
class Blog_model extends CI_Model {
function get_post($id)
{
// Join with user's table
// to get the name of the author
$this->db->join('posts', 'users.id = posts.user_id')
// THIS IS VERY HUGLY, But It's an other problem!
->where('posts.id', $id);
return $this->db->get('users')->result_array();
}
}
查看
<?php echo print_r($post); ?>
<br><br>
<?php echo print_r($comments); ?>
{post}
<h1>{title}</h1>
<i>By {name}</i>
<div class="post_body">{content}</div>
{/post}
<h2>Comments</h2>
<?php if($comments): ?>
{comments}
<h2>{commenter}</h2>
<div>{content}</div>
{/comments}
<?php else: ?>
<p>No comment...</p>
<?php endif; ?>
现在当我加载模板时,我会将帖子的标题传递给 模板库中title函数的第一个参数 (为了设置页面的标签,如帖子标题)
如果我链接页面(ex http://localhost/blog/index.php/blog/post/3
)
视图中的print_r
函数打印此结果
Array (
[0] => Array (
[id] => 3
[name] => Fra Ore
[password] => 123456
[email] => fra@ore.com
[title] => Very simple title!
[content] => bla bla bla
[user_id] => 1)
) 1
我必须在标题功能中添加什么内容?
我尝试了很多......
$this->template
->title($data[0][title])
->build('blog/post', $data);
但返回2通知
Use of undefined constant title - assumed 'title'
和
Message: Undefined offset: 0
controllers/blog.php
中的
想法?
答案 0 :(得分:0)
我认为问题在这里
class Blog_model extends CI_Model {
function get_post($id)
{
// Join with user's table
// to get the name of the author
$this->db->join('posts', 'users.id = posts.user_id') // THIS IS VERY HUGLY, But It's an other problem!
->where('posts.id', $id);
return $this->db->get('users')->row_array();
//--^^^^^^^^^---- here since is think this returns just a single row.
}
}
if($data['post'])
{
$this->template
->title($data['post']['title']) //<--- HERE
->build('blog/post', $data);
}
如果没有,那么我猜你需要使用循环来获得标题..
答案 1 :(得分:0)
试试这个:
if($data['post'])
{
$this->template
->title($data['post']['title'])
->build('blog/post', $data);
}
答案 2 :(得分:0)
我像你说的那样修改了控制器和模型:
<强>控制器强>
if($data['post'])
{
$this->template
->title($data['post']['title'])
->build('blog/post', $data);
}
<强>模型强>
class Blog_model extends CI_Model {
function get_post($id)
{
// Join with user's table
// to get the name of the author
$this->db->join('posts', 'users.id = posts.user_id') // THIS IS VERY HUGLY, But It's an other problem!
->where('posts.id', $id);
return $this->db->get('users')->row_array();
}
}
因此,标题模板功能设置正确,但视图中的解析器不起作用。 它返回括号中的代码:
{title}
By {name}
{content}
我认为将模型函数从row_array()更改为row()以返回对象,但问题仍然存在于解析器类中。
我看了here,但我不确定这是正确的方法......我不想修改CI文件...
帮助我!