2013-05-09 86 views
0

我想添加使用条件语句到这个基本引擎的能力,我试图发展,我不明白为什么它不会工作。谁能帮忙?它并没有取代文字。添加条件语句引擎

这里是template.php的条件语句

<?php 

class Template { 
    private $vars = array(); 

    public function assign($key, $value) { 
     $this->vars[$key] = $value; 
    } 

    public function render($file_name) { 
     $path = $file_name . '.html'; 

     if (file_exists($path)) { 

      $content = file_get_contents($path); 

      foreach ($this->vars as $key => $value) { 
       $content = preg_replace('/\{' . $key . '\}/', $value, $content); 
      } 

      $content = preg_replace('/\{if (.*)\}/', '<?php if ($1): ?>', $content); 
      $content = preg_replace('/\{elseif (.*)\}/', '<?php elseif ($1): ?>', $content); 
      $content = preg_replace('/\{else\}/', '<?php else: ?>', $content); 
      $content = preg_replace('/\{\/if\}/', '<?php endif; ?>', $content); 

      eval(' ?>' . $content . '<?php '); 

     } else { 
      exit('<h4>Engine error...</h4>'); 
     } 
    } 
} 

?> 

,这里是在HTML实施

<div class="container"> 
      <div id="content"> 
       <h3>{pagetitle}</h3> 
       <hr /> 
       <span>My name is {username} and I am {age} years old</span> 

       {if ({age}==21)} 
        21 
       {elseif ({age}==22)} 
        22 
       {else} 
        none 
       {/if} 

      </div> 
</div> 

它的字面打印出的条件块上面你看到它内嵌

+0

这是为什么这么难用一些存在的模板引擎或只是使用PHP? – 2013-05-09 19:26:56

+0

@George Cummins它真的打印出了{{if}'...到'{/ if}' – zachstarnes 2013-05-09 19:27:08

+0

@I我不拖延我只是想试试让所有人都这么做 – zachstarnes 2013-05-09 19:28:02

回答

1

我想你会需要使你所有的正则表达式模式都是不真实的。

做这样的事情:

/\{if (.*)\}/ 

将取代{if一审和}您更换的最后一个实例之间的一切。在这样的模式使用U标志进行匹配ungreedy:

/\{if (.*)\}/U 
+0

已经想到了。但是在解析之后,在$ content中不会有至少一个'<?php if(...):?>' – Lukas 2013-05-09 19:37:04

+0

@Lukas这就是我想的,由于某种原因,它不会工作。 – zachstarnes 2013-05-09 19:38:07

+0

@Mike勃兰特工作,但我不得不把结果放在一个标签,它出现 – zachstarnes 2013-05-09 19:38:41