Using CodeIgniter is it bad practice to load a view in a loop

后端 未结 3 1766
没有蜡笔的小新
没有蜡笔的小新 2020-12-20 09:45

I just got started with CodeIgniter and am wondering will it slow things down if I put code like this in a loop.

    $data[\'title\'] = \'the title\';
    $d         


        
相关标签:
3条回答
  • 2020-12-20 10:24

    Think about moving loop from controller to the view file (at controller you must prepare all data before load view file). You will have only one call for loading view file, and in the view file you can print out info in the loop cycle as you want.

    0 讨论(0)
  • 2020-12-20 10:37

    Loop in the view.

    <div>
        <?php foreach ($this->user_model->get_users() as $users): ?>
            <p><?php echo $user->first_name;?></p>
            <p><?php echo $user->last_name;?></p>
        <?php endforeach; ?>
    </div>
    

    This sample directly gets data from the model which has been many times been discussed in the codeigniter forums.

    0 讨论(0)
  • 2020-12-20 10:46

    I would not recommend calling your model from your view. This is not best practice when trying to keep to MVC framework standards. Call the model from your controller and pass the "users" array into the view as part of $data. Now you access the $users array just as a variable in the view. Similar to what you had, but this gets the access to the model back into the controller.

    Controller

    $data['title'] = 'the title';
    $data['content'] = 'blah blah blah';
    $data['users'] = $this->user_model->get_users();
    $this->load->view('result', $data);
    

    View

    <?php foreach ($users as $user) {
        echo '<p>' . $user->first_name . '</p>';
        echo '<p>' . $user->last_name . '</p>';
    }?>
    
    0 讨论(0)
提交回复
热议问题