Jump to content

Help with template class!


jimbob26

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.
Link to comment
Share on other sites

  • 5 months later...
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()
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.