将变量分配给视图

发布于 2024-12-19 11:02:14 字数 418 浏览 2 评论 0原文

将变量分配给视图的正确方法是什么?

$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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

多孤肩上扛 2024-12-26 11:02:14

第一种方法比第二种方法好得多,并且是将变量传递给视图的公认方法。

例如,假设您有两种观点。第一个视图显示系统中的所有用户,第二个视图显示当前登录的用户。这两个视图都循环遍历 $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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文