Skip to content

Commit 1fe4edf

Browse files
authored
Merge pull request #3 from cherry-framework/features/short-prints
Features/short prints
2 parents bfdc687 + 8817955 commit 1fe4edf

File tree

4 files changed

+29
-4
lines changed

4 files changed

+29
-4
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ Markup with PHP:
4040
<title>Hello, World!</title>
4141
</head>
4242
<body>
43-
<h1>Hello, <?php echo $name; ?>!</h1>
43+
<h1>Hello, {{ name }}!</h1>
4444
</body>
4545
</html>
4646
```

examples/templates/index.templater.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,6 @@
55
<title>Hello, World!</title>
66
</head>
77
<body>
8-
<h1>Hello, <?php echo $name; ?>!</h1>
8+
<h1>Welcome, {{ name }} {{ surname }}!</h1>
99
</body>
1010
</html>

examples/test.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,5 +10,6 @@
1010
$templateEngine = new Templater(__DIR__ . '/../examples/templates');
1111

1212
echo $templateEngine->render('index', [
13-
'name' => 'Temuri'
13+
'name' => 'Temuri',
14+
'surname' => 'Takalandze'
1415
]);

src/Templating/Templater.php

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,30 @@ private function _readeTemplate($template)
117117
return $content;
118118
}
119119

120+
/**
121+
* Prepare template content for caching.
122+
*
123+
* @param string $content Template content.
124+
*
125+
* @return string
126+
*/
127+
private function _normalizeContent($content)
128+
{
129+
// Check if content has short prints ( {{ variableToPrint }} )
130+
if (preg_match_all('/{{(.*?)}}/', $content, $matches)) {
131+
// Get all short pints and replace to php echo
132+
foreach ($matches[0] as $k => $v) {
133+
$changeMe = $matches[0][$k];
134+
$changeTo = '<?php echo $' . trim($matches[1][$k]) . '; ?>';
135+
136+
// Replace txt in content
137+
$content = str_replace($changeMe, $changeTo, $content);
138+
}
139+
}
140+
141+
return $content;
142+
}
143+
120144
/**
121145
* Cache given template.
122146
*
@@ -130,7 +154,7 @@ private function _cacheTemplate($content)
130154

131155
file_put_contents(
132156
$this->_cachedTemplatesDir . '/' . $contentHash . '.php',
133-
$content
157+
$this->_normalizeContent($content)
134158
);
135159
}
136160
}

0 commit comments

Comments
 (0)