是否可以将条件逻辑放在CodeIgniter视图? [英] Is it OK to put conditional logic on CodeIgniter Views?
问题描述
所以我现在处于一个两难的境地。我想在我的网站上实现一个登录按钮,当没有用户登录时会出现。但是,如果有人已经登录,我想将按钮更改为用户个人资料的链接。
我不知道正确的方法是在View中放置一个if语句,它根据从Controller传递的数据呈现不同的HTML,或者如果Controller需要决定是否用户是否登录,并将适当的数据结构传递给视图。
控制器用于计算和操作数据并将结果传递给
如果你应该使用 if
语句视图显示或隐藏一些标记,你是允许的!
但如果更改部分包含大量信息,我建议使用部分视图,并将其内容作为变量传递到主视图。
控制器:
class Foo extends CI_Controller {
public function bar()
{
/ /防止得到错误。
$ data ['partial'] ='';
//检查用户是否登录
if($ this-> session-> userdata('user_id')== TRUE){
$ data [ 'partial'] = $ this-> load-> view('partial / baz','',TRUE);
} else {
$ data ['partial'] = $ this-> load-> view('partial / qux','',TRUE);
}
$ this-> load-> view('my_view',$ data);
}
}
假设用户登录时,在CI会话中设置了
查看:
<?php echo $ partial; >
So I am in a dilemma at the moment. I want to implement a Login button on my site, which appears when no user is logged in. However, I want the button to change to a link to the user's profile if someone is already logged in.
I don't know if the right way to do this is to put an if statement in the View, which renders different HTML based on the data passed from the Controller, or if the Controller needs to decide if a user is logged in or not, and pass the appropriate data structures to the View. Which is the proper way to do it in CodeIgniter?
The controller is for calculating and manipulating data and passing the results to the view, and the view takes the results and render them to HTML.
If you should use if
statement in the view to show or hide some markup, you are allowed!
but if the changing section contains a lot of information, I suggest using partial views and passing their content as a variable to the main view. And doing all these in controller.
To do that in CodeIgniter:
Controller:
class Foo extends CI_Controller {
public function bar()
{
// prevent getting error.
$data['partial'] = '';
// check if user is logged in.
if ($this->session->userdata('user_id') == TRUE) {
$data['partial'] = $this->load->view('partial/baz', '', TRUE);
} else {
$data['partial'] = $this->load->view('partial/qux', '', TRUE);
}
$this->load->view('my_view', $data);
}
}
Assumption: user_id
is set in CI session when user log in.
View:
<?php echo $partial; ?>
这篇关于是否可以将条件逻辑放在CodeIgniter视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!