Last active
October 2, 2020 08:37
-
-
Save ricardofiorani/b44f67b3645fd27de8b39880b5c388e4 to your computer and use it in GitHub Desktop.
A simple example of framework-less PHP rendering templates to add translations (or any other dynamic content)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//Clean previous built files | |
array_map('unlink', glob(__DIR__ . '/public/*.html')); | |
array_map('unlink', glob(__DIR__ . '/public/pt-br/*.html')); | |
array_map('unlink', glob(__DIR__ . '/public/de/*.html')); | |
array_map('unlink', glob(__DIR__ . '/public/jp/*.html')); | |
//Scan for all templates | |
$templates = glob(__DIR__ . '/renderer/templates/*.php');; | |
$locales = glob(__DIR__ . '/renderer/locales/*.php');; | |
foreach ($templates as $templateFile) { | |
foreach ($locales as $localeFile) { | |
$renderedPage = renderPage($localeFile, $templateFile); | |
saveRenderedFile($templateFile, $localeFile, $renderedPage); | |
} | |
} | |
function renderPage($localeFile, $templateFile) | |
{ | |
ob_start(); | |
//Include translations | |
include $localeFile; | |
//Render the template itself | |
include $templateFile; | |
$contents = ob_get_contents(); | |
ob_end_clean(); | |
return $contents; | |
} | |
function saveRenderedFile($templateFile, $localeFile, $contents){ | |
$pageName = stripFilePath($templateFile); | |
$languageName = stripFilePath($localeFile); | |
if ($languageName == 'en') { | |
$fileDestination = __DIR__ . '/public/' . $pageName . '.html'; | |
} else { | |
$fileDestination = __DIR__ . '/public/' . $languageName . '/' . $pageName . '.html'; | |
} | |
//Save the output to the right file | |
file_put_contents($fileDestination, $contents); | |
echo $pageName . '.html concluded for language ' . $languageName . PHP_EOL; | |
} | |
function stripFilePath($filePath) | |
{ | |
return str_replace('.php', '', basename($filePath)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment