我在codeigniter框架中的库文件夹中创建了一个动态菜单。
class Left_menu {
private $ci;
function __construct()
{
$this->ci =& get_instance(); // get a reference to CodeIgniter.
}
function get_company ()
{
$html_out = '';
$company = $this->ci->db->query("select * from perusahaan");
$html_out .= "<ul class='sub_list'>";
foreach ($company->result() as $row)
{
$id = $row->id;
$name = $row->name;
$location = $row->location;
$html_out .= "<a href='".site_url("perusahaan_controller/detailPersahaan/".$id."")."'>";
$html_out .= "<li>".$name."</li>";
$html_out .= "</a>";
}
$html_out .= "</ul>";
$html = $html_out;
//print_r ($html);
return $html;
}
}
在视图中我称之为:
<?php $this->left_menu->get_company(); ?>
但是,它根本不显示菜单。如果我只打印它//print_r ($html);
,它就会打印出来,奇怪的是它打印菜单就像我想要返回它一样。 (看起来它将return
函数转换为print_r)。
答案 0 :(得分:2)
您无需为此创建库。
只需使用模型获取数据并将侧边栏注入当前控制器。
您可以通过创建名为sidebar的局部视图,并从模型中传递一些数据,然后将其插入当前视图来完成此操作。
class Controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->model('mymodel');
$data = $this->MyModel->get_data();
// call the sidebar view and pass it some data from model
// at this point the view is in the buffer so it can be manipulated before final output.
$sidebar = $this->load->view('sidebar', array(
'data' => $data
), true);
return $this->load->view('index', array(
'sidebar' => $sidebar
));
}
}
class MyModel extends CI_Model
{
public function __construct()
{
parent::__construct();
}
public function get_data()
{
$query = $this->db->get('perusahaan');
return ( $query->num_rows() > 0 ) ? $query->result() : false;
}
}
<ul class="sublist">
<?php foreach($data as $_data): ?>
<li id="<?php echo $_data->id;?>">
<a href="<?php echo ".site_url('perusahaan_controller/detailPersahaan/')."/".$_data->id.""><?php echo xss_clean($_data->name);?></a>
</li>
<?php foreach; ?>
</ul>
<aside class="sidebar">
<?php echo $sidebar; ?>
</aside>
<div>
//... content
</div>