Page 1 of 1

Template system

Posted: Wed Aug 10, 2005 6:08 pm
by Sander
I'm going to make an attempt at making a template system, but I need some opinions on how exactly I should do this.

The way I see it, I could do it in 2 different ways:

1) Using the 'eval' function, making it possible to simply make some variables in the script and use those in the output, like this:

Code: Select all

<?php
$title = 'Testing Template System.';
echo eval($tpl->out('MAIN'));'

/* this is what is being returned by the eval:

<html>

<head>
<title>$title</title>
</head>

<body>
Stuff
</body>

</html>
*/
?>
That code works perfectly. I can simply make some variables with content and after that output them with the eval. No need for any fancy stuff. The problem is that this his some security risks, though.

2) Replacing variables. I believe this is how most template engines work. I create an array (probably in the template class) which has all the data that goes into the HTML. Using functions like 'strtr' or 'str_replace' (I don't even know which function would be best for this) I would first replace certain code in the HTML with the variables before I output it.

I'm not sure which of those 2 methods would be best. If anyone could give me some tips on this, it would be much appreciated :)

Thanks.

Posted: Wed Aug 10, 2005 6:33 pm
by feyd
two is far far far safer, however there are several engines that use both, or one. I prefer doing two myself, as I can do a single pass with a regular expression to actually do the substitution. Granted, there may be logic required, so you will need to come up with a way of determining where logic needs to happen and how it's to be handled, but you'd have to do that in either case. :)