Add the missing parse_string () so

    imageIn March , news appeared from the Wave habrayuzer , which made the hearts of all fans of the CodeIgniter framework tremble: version 2.0 of this lyalyka is about to appear. And now, more than two months have passed, and things are still there, the “dvushka” is not available for downloading from an offsite. And everything would be alright, but the method that they promised to implement in the second version of the framework, parse_string () in the Parser class, which would allow us to parse templates not only from files, but also from variables, was very lacking. And since in one of my developments there is a need to store small templates in the database, then, so to speak, it has become unbearable for me. Praise to the developers, we were given the opportunity to extend all the standard classes, which we will use.





    For the implementation of this method - welcome to the Habrokat.

    So, in order to expand the functionality of the Parser class, create the file " MY_Parser.php " in the directory " application / libraries ". Insert the following code inside the file:

    1. <?php
    2. class MY_Parser extends CI_Parser{
    3.   function parse_string($string = "",$values = array(),$return = false){
    4.  
    5.       foreach ($values as $key => $val){
    6.         if (is_array($val))
    7.         {
    8.           $string = $this->_parse_pair($key, $val, $string);    
    9.         }
    10.         else
    11.         {
    12.           $string = $this->_parse_single($key, (string)$val, $string);
    13.         }
    14.       }
    15.     
    16.     $CI =& get_instance();
    17.     ob_start();
    18.     foreach ($values as $key => $val)
    19.       $$key = $val;
    20.  
    21.     echo eval('?>'.preg_replace("/;*\s*\?>/", "; ?>", str_replace('<?=', '<?php echo ', $string)));
    22.     $string = ob_get_contents();
    23.     @ob_end_clean();
    24.     if ($return) return $string;
    25.     $CI->output->append_output($string);
    26.   }
    27. }
    28. ?>
    * This source code was highlighted with Source Code Highlighter.


    That's all! Now the new parse_string () method will be available from anywhere, wherever you connect the Parser library.

    This method accepts the parameters almost identical to those requested by the parse method, except that the first parameter, instead of the path to the template file, is a string variable containing the text of the template. The second parameter is also an array with variables, and the third indicates how the method returns the processed template - return to a variable, or directly to output.

    I hope someone this small addition to CodeIgniter 1.7.2 will be useful while waiting for a full 2.0 release.

    Until we meet again;)

    Also popular now: