[eluser]bugboy[/eluser]
Hi all
This is a little contribution to the community.
I've recently been working on a project which included the Amazing Library Modular Extension (me hmvc) and wanted to use the codeignitor Parser class as well as its pretty simple and easy to use.
I came across a challenge which while not detrimental to the system i thought it would be nice to keep coding conventions the same.
In some of my views i was calling this code to load my blog calendar in the sidebar as a partial.
Code:
<?php
echo modules::run('blog/cal');
?>
This seemed to be confusing to a user who was happily using:
Code:
{title}
{blog_entries}
{/blog_entries}
So i thought to myself wouldn't be nice to be able to load these partials in the same manor to keep things easy to my users.
I came up with this.
MY_Parser.php file:
Code:
class MY_Parser extends CI_Parser {
/**
* Parse a template
*
* Parses pseudo-variables contained in the specified template,
* replacing them with the data in the second param
*
* @access public
* @param string
* @param array
* @param bool
* @return string
*/
function parse($template, $data, $return = FALSE)
{
$CI =& get_instance();
$template = $CI->load->view($template, $data, TRUE);
// parse the template for module partials call
$template = $this->_parse_modules($template);
if ($template == '')
{
return FALSE;
}
foreach ($data as $key => $val)
{
if (is_array($val))
{
$template = $this->_parse_pair($key, $val, $template);
}
else
{
$template = $this->_parse_single($key, (string)$val, $template);
}
}
if ($return == FALSE)
{
$CI->output->append_output($template);
}
return $template;
}
// --------------------------------------------------------------------
/**
* Parse for modules
*
* @access private
* @param string
*/
function _parse_modules($template)
{
// look for {'anything':'anything'}
$template = preg_replace_callback("/{(.*):(.*)}/", array( &$this, '_insert_module'), $template);
return $template;
}
/**
* inserts modules
*
* @access private
* @param string
*/
function _insert_module($matches)
{
$load = '';
if($matches[1] === 'module')
{
$load = $matches[2];
}
else
{
$load = $matches[1].'/'.$matches[2];
}
return modules::run($load);
}
}
This now allows me to use these calls in my templates to call the blog calendar partial
This is the only area I'm not happy with which is if i want to call the base controller for a module (index) you have to use this
Now this may not be the best way or the most efficient way to do this but i thought i'd show this code and it maybe helpful to someone.