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!
Basically, I'm thinking of making my own template system. Obviously the variable replacements part is easy...but I'm having trouble contemplating how I'm going to evaluate "if" statements.
I've managed to parse simple statements...using regex to turn it into PHP syntax, and eval() - ing the compiled code.
However, this has the limitation of being unable to handle more complex "if" statements, including elseif and else statements. I've had a look through phpBB and smarty's source...but can't figure it out. Google seems to yield no help either...
So I was just wondering if anyone had any experience with this, or had any ideas on how I would go about implementing this?
Couldn't see any suggestions about if() statements though...That's what I'm particularly interested in.
I've had a go at doing this before, but when I got to parsing if() statements, I just gave up.
And yeah...the contraversy about using a template language...meh. I don't know if I'm actually going to use this, ever...I just thought it'd be fun to try.
I am absolutely clueless about these if statements though...any help or suggestions would be great.
I am interested in this too. I think the if() part will in place once we can get the template broken into a hierarchy of nested blocks. The you would just run through the blocks and see if they are an if()/while()/for()/foreach(). My initial guess would be to use regexp to get offsets in the text for the starts and ends of all blocks. Then run through that to determine the nesting.
I am assuming that you do not want to use eval() for these templates, since that would negate the only benefit that non-PHP templates have -- security.
PS - I think many of these template systems compile into PHP code and run those templates from a cache
That's why I was thinking that the first pass is just dealing with the starts and ends of blocks. Then you ladder walk through the two arrays of offsets to deal with the nesting and what the actual statements are. Quick hack, but maybe start with something like this:
Idk, I just think it's neater to separate the syntax and formatting.
Although I see there have been many discussions on how this should be done from the threads posted by arborint
I've just had the idea of using strpos() to loop through each if statement. Then match up the opening brackets to their closing brackets...hopefully being able to capture whatever's in the middle.
I cba to have a go right now...I'll play around with it tomorrow though
EDIT
Oh, hey, arborint...I see you've had the same idea Yeah...I reckon that's the way to go.