Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it OK to put conditional logic on CodeIgniter Views? [closed]

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?

like image 793
Ermir Avatar asked Jun 26 '13 10:06

Ermir


People also ask

Is CodeIgniter case sensitive?

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.

Why $This is used in CodeIgniter?

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.

What is the use of views in CodeIgniter?

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.


2 Answers

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
}
like image 127
ABorty Avatar answered Oct 13 '22 11:10

ABorty


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; ?>
like image 44
Hashem Qolami Avatar answered Oct 13 '22 10:10

Hashem Qolami