Jump to content


Photo

Help with template class!


  • Please log in to reply
2 replies to this topic

#1 jimbob26

jimbob26
  • Members
  • Pip
  • Newbie
  • 3 posts

Posted 26 February 2006 - 12:53 AM

Hello, i current have this class for a template:
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();

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:

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

and the html file:
{startloop}
{item}
{endloop}

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

so far i have:

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]);
            }
      }
}

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

#2 hostfreak

hostfreak
  • Members
  • PipPipPip
  • Advanced Member
  • 581 posts

Posted 11 August 2006 - 03:52 PM

Shouldn't:
$template = new template;
Be:
$template = new template();

?

#3 High_-_Tek

High_-_Tek
  • Members
  • PipPipPip
  • Advanced Member
  • 72 posts

Posted 11 August 2006 - 04:27 PM

No,

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

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

The array structure is like so:

var ref in html file => real value

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




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users