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?
It's not consistent. Some will search for the name as is and if it doesn't find it it checks to see if a lower-cased version exists and loads that if it does.
To actually answer your question, $this actually represents the singleton Codeigniter instance (which is actually the controller object). For example when you load libraries/models, you're attaching them to this instance so you can reference them as a property of this instance.
A view is simply a web page, or a page fragment, like a header, footer, sidebar, etc. In fact, views can flexibly be embedded within other views (within other views, etc., etc.) if you need this type of hierarchy. Views are never called directly, they must be loaded by a controller.
In Codeigniter,you can put if and else statement in view.
if($this->session->userdata('your_session_variable'))
{
?>
<a href="profile_page_link">Profile</a>
<?php
}
else
{
?>
<a href="login_page_link">Login</a>
<?php
}
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; ?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With