2017-04-05 10 views
0

を持つ:https://stackoverflow.com/a/17870094/2081511私は、この提案あたりのテンプレートエンジンとしてPHPを使用していますテンプレートエンジンとしてPHPを使用して、薄いテンプレート

私が持っている:

$title = 'My Title'; 
ob_start(); 
include('page/to/template.php'); 
$page = ob_get_clean(); 

、ページ上//template.phpに私は持っています:

他人が独自のテンプレートを開発しやすくするために、テンプレートページから必要な構文のいくつかを削除しようとしています。私は何をしたいのテンプレートファイルからこれらの行を{$変数}の変数の命名規則を保持するが、削除され:

<?php 
echo <<<EOF 
EOF; 
?> 
私には、文のいずれかの側にそれらを置くことについて考えていた

が、それをその文を含めるのではなく、その文をテキストとして表示するだけです。

+1

のようになります役立つかもしれない、私は知りません{$ title}を<?= $ titleに置き換えるのに足りない。 ?>が、マークアップを増やし複雑になります。口髭やハンドルバーなどのテンプレートシステムを見たことがありますか?エンドユーザには簡単な構文{{title}}がありますが、これはPHPに慣れていません – bumperbox

+0

'page/to/template.php'は何かをエコーし​​ますか? '$ page'で何をしていますか? – PHPglue

+0

PHPの '{$ title}'の '@ bumperbox'は二重引用符で囲まれています。 '{}'は '{$ obj-> title}'や '{$ singleDimensionalArray [$ number]}'のような状況です。 – PHPglue

答えて

0

さて、何がやりたいことは可能であるならば、あなたは非常にシンプルなテンプレートソリューションをしたい場合、これは

<?php 


$title = 'My Title'; 

// Instead of including, we fetch the contents of the template file. 
$contents = file_get_contents('template.php'); 

// Clone it, as we'll work on it. 
$compiled = $contents; 

// We want to pluck out all the variable names and discard the braces 
preg_match_all('/{\$(\w+)}/', $contents, $matches); 

// Loop through all the matches and see if there is a variable set with that name. If so, simply replace the match with the variable value. 
foreach ($matches[0] as $index => $tag) { 
    if (isset(${$matches[1][$index]})) { 
    $compiled = str_replace($tag, ${$matches[1][$index]}, $compiled); 
    } 
} 

echo $compiled; 

テンプレートファイルは、この

<html> <body> {$title} </body> </html> 
関連する問題