Jump to content

Archived

This topic is now archived and is closed to further replies.

jimbob26

Help with template class!

Recommended Posts

Hello, i current have this class for a template:
[code]
class template {
   function load($filepath) {
      $this->template = file_get_contents($filepath);
   }
   function replace($var, $content) {
      $this->template = str_replace("{$var}", $content, $this->template);
   }
   function display() {
        print $this->template;
   }
}
$template = new template;
$template->load("html_file.htm");
$template->replace("{item}", "replaced item!!");
$template->display();
[/code]

and the html file contains {item} in it and when the script is run, it replaces the "{item}" with "replaced item!!". However, I now want to repeat the replacment so its like this:

[code]
$template->replace("{item}", array("Item 1","Item 2","Item 3","Item 4"));
[/code]

and the html file:
[code]
{startloop}
{item}
{endloop}
[/code]

I need some help so that the {item} is replaced and repeated so that all values in the array appear.

so far i have:

[code]
function replace($var, $content = array()) {
      if(preg_match ("#(\{startloop\})(.+?)(\{endloop\})#", $this->template, $middle)) {
            foreach($content as $content_array) {
                  $this->template = str_replace("{$var}", $content_array, $middle[2]);
            }
      }
}
[/code]

However this does not work... any help would be much appreciated. Thanks in advance, jimbob.

Share this post


Link to post
Share on other sites
Shouldn't:
[code]
$template = new template;
[/code]
Be:
[code]
$template = new template();
[/code]

?

Share this post


Link to post
Share on other sites
No,

And you could re-write your replacement func like so..

[code]
function replace($array) {
foreach ($array as $ref => $value) {
$somevar = preg_replace("#\{".$ref."\}#i", $value, $somevar);
}
}
[/code]

The array structure is like so:

var ref in html file => real value

And the $somevar is the code retrieved using file_get_contents()

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.