Load Random Views in CodeIgniter (Reactor 2.0)

Perfect for loading a random testimonial, banner image, etc.  A quick helper for your coding pleasure = )

First, create your helper (helpers/randomview_helper.php).  Here are the contents:


<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Random view
*/
function get_random_view($fullpath, $viewpath)
{
$file = str_replace('.php', '', random_element(get_filenames($fullpath)));
return $viewpath.$file;
}

Notice that random_element and get_filenames are both used.  These are also CodeIgniter helpers which are included in Reactor 2.0.  From your controller, load the helpers, call the get_random_view function and pass the data to your view:


//Get a random testimonial
$this->load->helper(array('file', 'array', 'randomview'));
$data['testimonial'] = get_random_view('application/views/sell/testimonials/', 'sell/testimonials/');

Notice that you’re passing both the full path to the folder where your view file is, as well as the path that the view loader well you. Now, when you load your main view, just make sure you pass in the $data array:


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

In the view you just loaded, you can now use your $testimonial variable to call your random view:


load->view($testimonial);?>

UPDATE 03/06: Added support for getting an array of random views (for example, if you want to randomize testimonials):


/**
* Returns an array of all views
*
* @param string
* @param string
* @return string
*/
function get_random_views($fullpath, $viewpath)
{
$file_array = str_replace('.php', '', get_filenames($fullpath));
$file_count = count($file_array);

$keys = array_keys($file_array);
shuffle($keys);
$random = array();
foreach ($keys as $key)
{
$random[$key] = $viewpath.$file_array[$key];
}
return $random;
}

Have fun = )

This entry was posted in CodeIgniter, Programming. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>