Welcome Guest, Not a member yet? Register   Sign In
How can I avoid using foreach in a view?
#1

[eluser]victorche[/eluser]
I've read a lot about pros/cons of using foreach in a view file. Even according to this thread:
http://ellislab.com/forums/viewthread/170579/
Using of foreach is something good ... But let me explain the problem. I am having an array of data, which should be displayed in a view. This data is taken from the database directly but I want to change some of the values, to be ... more human let's say. So the first case is to use foreach in the view like this:
Code:
<?php foreach ($received as $row): ?>
<span>&lt;?php echo $row['id']; ?&gt;</span><span>&lt;?php echo $row['description']; ?&gt;</span><span>&lt;?php echo $row['time']; ?&gt;</span>
&lt;?php endforeach; ?&gt;
Perfect so far ... but even in this small example, I have 2 values that need to be changed a little. Let me show you the case, if this foreach is made in the controller:
Code:
$received = $this->tasks->received_tasks($user_id);

        if ($received)
        {
            foreach ($received as $row)
            {
                $tasks[] = array(
                    'id' => $row['task_id'],
                    'description' => character_limiter($row['description'], 60),
                    'time' => nice_time($row['time'])
                );
            }
        }
We have 2 things here ... I can use the text helper to cut the description and i can use a little helper which will make the time more human, like "2 weeks ago". How can I do the same if the foreach loop is in the view?
It is really hard for me to understand why we have to do the loop in the view files. Can I somehow avoid this?
Or how can I use these nice helpers if the loop is in the view?
Please, give advice Sad
#2

[eluser]Cristian Gilè[/eluser]
Helpers are available in the view so you can do:

Code:
&lt;?php foreach ($received as $row): ?&gt;
<span>&lt;?php echo $row['id']; ?&gt;</span><span>&lt;?php echo character_limiter($row['description'],60); ?&gt;</span><span>&lt;?php echo nice_time($row['time']); ?&gt;</span>
&lt;?php endforeach; ?&gt;

If you don't want the foreach statements in the view you can build the html block in the controller, save it in a variable and pass it in the view:

Code:
$data = array();
$data['html_block'] = '';

foreach ($received as $row)
{
   $data['html_block'] .= '<span>'.$row['task_id'].'</span><span>'.character_limiter($row['description'], 60).'</span><span>'.nice_time($row['time']).'</span><br/>';
);
}

$this->load->view('view_name',$data);

In your view:

Code:
echo $html_block;


I prefer to use foreach in the view.


Cristian Gilè




Theme © iAndrew 2016 - Forum software by © MyBB