Welcome Guest, Not a member yet? Register   Sign In
Using template tags with data coming from a database
#2

[eluser]pistolPete[/eluser]
The template parser class ist the way to go, but it expects the view to be a local file.
So you have to extend the parser class.
The following code adds a method parse_string() to the parser class which allows you to parse a string coming from db.
Code:
class MY_Parser extends CI_Parser {

    /**
     *  Parse a template string, which is NOT a file but
     *  is e.g. a result of a database query
     *
     * 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_string($template, $data, $return = FALSE)
    {
        $CI =& get_instance();
        
        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;
    }
}

Usage:
Code:
// the data which should be used instead of the {variables}
$data = array(
            'today' => date(DATE_RFC822),
            'some_other_data' => 'insert value here'
            );

// get an entry from database
$this->db->select('entry');
$query = $this->db->get('table_name');
$result = $query->row_array();

// parse the entry
$this->load->library('parser');
$parsed_string = $this->parser->parse_string($result['entry'], $data, TRUE);
// do something view your parsed string, e.g. load into another view.

The code is untested, so please report back if its working.


Messages In This Thread
Using template tags with data coming from a database - by El Forum - 02-26-2009, 12:15 AM
Using template tags with data coming from a database - by El Forum - 02-26-2009, 02:08 AM
Using template tags with data coming from a database - by El Forum - 07-07-2009, 01:47 PM



Theme © iAndrew 2016 - Forum software by © MyBB