Template system

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Sander
Forum Commoner
Posts: 38
Joined: Sat Aug 06, 2005 12:43 pm

Template system

Post 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.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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. :)
Post Reply