Používam PHP ako šablónový motor na tento návrh: https://stackoverflow.com/a/17870094/2081511
Mám:
$title = "My Title";
ob_start();
include("page/to/template.php");
$page = ob_get_clean();
A na stránke / do / template.php mám:
<?php
echo <<<EOF
<!doctype html>
<html>
<title>{$title}</title>
...
EOF;
?>
Snažím sa odstrániť niektorú požadovanú syntaxz stránok šablóny, aby bolo pre ostatných jednoduchšie vytvárať vlastné šablóny. Čo by som chcel urobiť, je zachovať konvenciu pre menovanie premenných {$ variable}, ale odstrániť tieto riadky zo súboru šablóny:
<?php
echo <<<EOF
EOF;
?>
Premýšľal som o tom, že ich budem umiestňovať na oboch stranách výkazu zahrnúť, ale potom by mi to len ukázal ako text ako namiesto toho, aby som ho zahrnul.
odpovede:
0 pre odpoveď č. 1No, ak chcete veľmi jednoduché šablónové riešenie, mohlo by to pomôcť
<?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;
Súbor šablón by vyzeral takto
<html> <body> {$title} </body> </html>