Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I don't understand the logic behind the way template engines parse loop, statements and that sort of stuff. I mean template engines other then a PHP template engine.

Doing this to learn PHP better mainly, and I've always wanted to see if I could.

Here's what I've tried:

Let's say I have the following in my template file:
<if>$variable != true</if>
// My Code
<elseif>$variable == 'apples'</elseif>
// My Code
</endif>

To parse that, I've tried the following variants:
PHP
<?php
$contents = preg_replace("/\<if\>(.*)\<\/if\>/", "<?php if($1) {", $contents);
$contents = preg_replace("/\<elseif\>(.*)\<\/elseif\>/", "} elseif($1) {", $contents);
$contents = str_replace("</endif>", "} ?>", $contents);
 
$contents = eval($contents);
?>

Which if I echo before I eval it, I get the following:
<?php if($variable != true) {
// My Code
} elseif($variable == 'apples') {
// My Code
} ?>

And after I eval, I get the following error:
Parse error: syntax error, unexpected '<' in C:\xampp\htdocs\www\hmvc\includes\template_engine.php(84) : eval()'d code on line 1

The entire page I'm trying to eval, looks like:
<html>
  <head>
    <title>Test View Template Engine</title>
  </head>
  <body>
    <p>This is test, huh? My Title</p>
    <p>Testing the test</p>
    
    
      <?php if($variable != true) {
      // My Code
      } elseif($variable == 'apples') {
      // My Code
      } ?>

  </body>
</html>


I've also tried the following variant:
PHP
$match = array();
preg_match_all("/\<if\>(.*)\<\/if\>/", $contents, $match[1]);
preg_match_all("/\<\/if\>(.*)\<elseif\>/", $contents, $match[2]);
preg_match_all("/\<elseif\>(.*)\<\/elseif\>/", $contents, $match[3]);
preg_match_all("/\<\/elseif\>(.*)\<\/endif\>/", $contents, $match[4]);
print_r($match);

Which gives me the following array:
Array
(
  [1] => Array
    (
      [0] => Array
        (
          [0] => <if>$variable != true</if>
        )

      [1] => Array
        (
          [0] => $variable != true
        )

    )

  [2] => Array
    (
      [0] => Array
        (
        )

      [1] => Array
        (
        )

    )

  [3] => Array
    (
      [0] => Array
        (
          [0] => <elseif>$variable == 'apples'</elseif>
        )

      [1] => Array
        (
          [0] => $variable == 'apples'
        )

    )

  [4] => Array
    (
      [0] => Array
        (
        )

      [1] => Array
        (
        )

    )

)

For some reason the preg_match_all is not finding the stuff between </endif> and </elseif> and between <elseif> and </if>...

Thanks for any productive comments/help. Good day!
Posted
Updated 5-Apr-14 18:17pm
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900