views:

93

answers:

2

Ive been working some time on own template engines but i alwais get stuck in strucktured documents like

<block : block1>
    <table>
        <block : row>
            <tr>
                <td>
                    {value}
                </td>
                <td>
                    {value2}
                </td>
            </tr>
        </block>
    </table>
</block>

I can get "block 1" with a regex but it will break at the first (the one of "row")

But i want a smarter way (and not by using a function like DOM) i was thinking about something like

while($i < strlen($code)){
    if(substr($code,$i,1)){
        //tag is opened
    }
}
A: 

I am not entirely sure about what your question is, but there has been a lot of debating about templating languages in PHP but I think a general consensus reached by now was that it usually doesn't make much sense to roll your own templating language. You might get instant nice result by e.g. using string replacement and regular expressions, but eventually you will need more functionality like loops or other expressions and then it will become quite tricky (ultimately ending in creating your own compiler).

The best suggestion usually is to either use PHP as your templating language directly (that is what PHP was designed for in the first place and with strictly following the MVC pattern quite a good solution, too) or try one of the existing templating engines. Only if you can't make any of them fit your needs (most of them are extensible through a plugin mechanism) you should start making your own.

Daff
+2  A: 

Basically, you're constructing a programming language here (albeit simple, it's still a programming language). To interpret a programming language you need a compiler, which usually contains a lexer (which splits input stream into meaningful tokens) and a parser (which reads tokens one by one and takes whatever actions are needed). In your simplified example, the lexer would be probably regexp-based, and the parser can be a simple stack-based one.

(terms in italic should actually be wikipedia links).

stereofrog