将变量分配给视图
将变量分配给视图的正确方法是什么?
$data['users'] = $this->users_model->get_all();
$this->load->view('users', $data);
// and inside users.php view: foreach($users as $user) {}
或者
$this->users = $this->users_model->get_all();
$this->load->view('users');
// and inside users.php view: foreach($this->users as $user) {}
对于这种情况有一般规则吗?
what is the proper way of assigning variables to views?
$data['users'] = $this->users_model->get_all();
$this->load->view('users', $data);
// and inside users.php view: foreach($users as $user) {}
OR
$this->users = $this->users_model->get_all();
$this->load->view('users');
// and inside users.php view: foreach($this->users as $user) {}
Are there general rules for that type of situations?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
第一种方法比第二种方法好得多,并且是将变量传递给视图的公认方法。
例如,假设您有两种观点。第一个视图显示系统中的所有用户,第二个视图显示当前登录的用户。这两个视图都循环遍历
$users
变量并输出他们的名称。使用第二种方法,您必须在加载每个视图之前将适当的数据分配给$this->users
。对于给定的请求,必须在所有加载的视图之间使用唯一的变量名称将会失控。此外,某些视图可能变得相当复杂。将视图中所需的每个变量分配给控制器的属性是没有任何意义的。
The first way is much better than the second and is the accepted way of passing variables to views.
For example, say you have two views. The first view displays all users in the system and the second view displays the users that are currently logged in. Both views loop over a
$users
variable and output their names. Using your second method you would have to assign the appropriate data to$this->users
before loading each view. Having to use unique variable names between all loaded views for a given request would get out of hand.Additionally, some views can become quite complex. It wouldn't make any sense to assign each variable you need in a view to a property of your controller.