Jump to content

trying to make a simple template system


dezkit

Recommended Posts

Hey guys first of all I got 3 files -

 

index.php

require_once('/libs/template.class.php');

$template = new Template;

$template->assign("title","test");

 

template.php

<?php echo $title; ?>

 

template.class.php

function assign($var, $val)
    {
        $var = $val;
    }

 

I'm trying to assign a variable in index.php, then recall it in the template.php, how would I go about this?

 

Thank you!

Link to comment
https://forums.phpfreaks.com/topic/213947-trying-to-make-a-simple-template-system/
Share on other sites

Why use php in your template file? I mean, how does that differ from your index.php code?

 

Stripping PHP out of your template file can nicely separate your HTML code from your PHP code. Below is a rough outline of a useable token-replacement template class, which parses an html file.

 

class.template.php

class Template {
public $template;

public function __construct($template) {
	$this->template = file_get_contents($template);
}

public function assign($replacement, $new_content) {
	$this->template = str_replace("{$replacement}", $new_content, $this->template);
}

public function get_template() {
	return $this->template;
}
}

 

index.php

require_once('class.template.php');

$template = new Template('template.html');
$template->assign('{ReplaceThisText}', 'WithThisText');
echo $template->get_template();

 

template.html

<html>
    <body>
        {ReplaceThisText}
    </body>
</html>

 

This is not meant to be used as is, but give you an idea of how to expand this further.

Archived

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

×
×
  • 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.