Welcome Guest, Not a member yet? Register   Sign In
Dynamic pseudo variables template parses
#1

[eluser]MaartenDeGroote[/eluser]
Hi all,

This is probably kinda simple but I can't seem to get the hang of it. I want to make use of the template parsing class and the pseudo-variables.

Now, let's say I had the following code:

Code:
{blog_entries}
  {blog_title}
  {blog_post}
{/blog_entries}

Instead of using the word "blog_entries", I want to make use of a dynamic key. For example: if I had a table with image gallery names and each gallery contains images, then I wanted the "blog_entries" variable to be replaced by the name of the gallery. Like this:

Code:
{vacations}
  {img}
{/vacations}

{portraits}
  {img}
{/portraits}

Where "variations" and "portraits" are variable names, selected from a database table.

I know it is a bit confusing, but I hope I get the message across!

Thanx alot!
#2

[eluser]Aken[/eluser]
There's two ways I've found you can do this:

The first way is kind of a fun trick, but may not be the most reliable. The template parser library goes through the loop of data to parse in order. You can double brace a variable and it will be parsed twice, as long as you put your data variables in the correct order. Example:
Code:
// VIEW
Here is the replaced variable: {{varname}}

// CONTROLLER

$this->load->library('parser');

$data = array(
    'varname'    => 'variable',
    'variable'    => 'replaced variable!',
);

$this->parser->parse('template', $data);

What happens is the variable {varname} is replaced, leaving the variable structure {variable} left in the view. Then, on the next iteration, {variable} is replaced with the appropriate content.

I'm not sure how fool proof this is, but it does heavily rely on having your variable put in a specific order, which may or may not be difficult in your situation.

The other method is to set any variables you want to use and pass them to a view. You then return the view as a string instead of loading it, and use $this->parser->parse_string() instead of parse().
Code:
// VIEW
<h1>Galleries</h1>

&lt;?php foreach ($galleries as $g): ?&gt;
<div>

{&lt;?php echo $g; ?&gt;}
    {img}
{/&lt;?php echo $g; ?&gt;}

</div>
&lt;?php endforeach; ?&gt;

// CONTROLLER

$this->load->library('parser');

$viewdata = array(
    'galleries'    => array('vacations', 'portraits'),
);

// Return view as string, now filled with proper template variables.
$template = $this->load->view('template', $viewdata, true);

$replace = array(
    'vacations'    => array(
        array('img'    => 'vacation img'),
    ),
    'portraits'    => array(
        array('img'    => 'portrait img'),
    ),
);

// Parse the view string, instead of a standard view. Works the same way.
$this->parser->parse_string($template, $replace);

Hope that helps you out.




Theme © iAndrew 2016 - Forum software by © MyBB