Rozbudowujemy nasz template engine o kolejne dyrektywy. Do dzieła.
Nasz sth3.php wygląda już tak:
<h1>{{ $site_name }}</h1>
@if(isset($name))
<p> Hello [b]{{ $name }}[/b]</p>
@else
<p>Hello guest</p>
@endif
Musimy dodać wzory:
<?php
class TemplateEngine
{
private array $globalTemplateData = [];
protected static $patterns = [
[
"pattern" => '/\{\{\s*(\$.*?)\s*\}\}/',
"replace" => "<?php echo $1; ?>"
],
[
"pattern" => '/\[b\](.*?)\[\/b\]/s',
"replace" => "<b>$1</b>"
],
[
"pattern" => '/@if\((.*)\)/',
"replace" => "<?php if ($1) : ?>"
],
[
"pattern" => '/@else/',
"replace" => "<?php else : ?>"
],
[
"pattern" => '/@endif/s',
"replace" => "<?php endif; ?>"
],
];
//(...)
}
I to w zasadzie wszystko – teraz testujemy:
$template = new TemplateEngine(__DIR__);
$template->addGlobal('site_name', 'MyApp');
echo $template->renderTemplate('sth3.php', ['name2' => 'John']);
Zamieńmy name2 na name a zamiast hello guest dostaniemy hello john.
$template = new TemplateEngine(__DIR__);
$template->addGlobal('site_name', 'MyApp');
echo $template->renderTemplate('sth3.php', ['name' => 'John']);