1

I have a model that returns a list of artist's names from a database along with their ID. I want to loop through these artists in my view and create links to their pages with the following format:

http://www.example.com/the-artist-name/artist-portfolio/ID.html

What is the best way to do this?

tereško
  • 58,060
  • 25
  • 98
  • 150
freshest
  • 6,229
  • 9
  • 35
  • 38

2 Answers2

0

Controller

$data['artists'] = $this->artists_model->get_all(); // should return array
$this->load->view('yourview', $data);

View

<?php foreach($artists as $artist): ?>
    <a href="http://example.com/<?php echo $artist['name']; ?>/artist-portfolio/<?php echo $artist['id']; ?>.html">
        <?php echo $artist['name']; ?>
    </a>
<?php endforeach; ?>
Chris G.
  • 3,963
  • 2
  • 21
  • 40
  • Do you know how to do this in the model? i.e. make the view cleaner? – freshest Sep 22 '11 at 15:34
  • Models make controllers cleaner. Controllers make views cleaner. Put your Database and validation rules in the model and prepare arrays in the controller and send them to the view. Loop over them inside the view. This is about as clean as a view will be. – Chris G. Sep 22 '11 at 16:29
0

Pass the data from the model into the view and loop through it like you normally would.

In your controller:

$view_data['artists'] = $this->artist_model->get_artists();
$this->load->view('view.php', $view_data);

In your view:

foreach ($artists as $artist) {
    echo "<a href=\"http://www.example.com/{$artist['name']}/artist-portfolio/{$artist['id']}.html\">{$artist['name']}</a>";
}
birderic
  • 3,745
  • 1
  • 23
  • 36
  • Is codeigniter smart enough to load `view.php`? I have never included a file extension in my `view()` calls. – Chris G. Sep 22 '11 at 14:43
  • The file extension does not need to be specified unless you use something other than `.php`. – birderic Sep 22 '11 at 14:45