Skip to content

Instantly share code, notes, and snippets.

@mlaopane
Last active July 25, 2019 05:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mlaopane/be813022d284a5e10115071366061a9c to your computer and use it in GitHub Desktop.
Save mlaopane/be813022d284a5e10115071366061a9c to your computer and use it in GitHub Desktop.
A class to render and create html/twig templates
<?php
/**
* This class allows to :
* - render templates from a basePath
* - create/update templates from nothing or using an existing template as a base
*
*/
class Templating
{
/**
* @var string
*/
public $basePath = null;
/**
* @var HtmlCleaner
*/
private $cleaner = null;
/**
* @var string
*/
public $identifier = null;
public function __construct(HtmlCleaner $cleaner, string $basePath, string $identifier = "{identifier}")
{
$this->basePath = $basePath;
$this->cleaner = $cleaner;
$this->identifier = $identifier;
}
public function render(string $templateName): string
{
/**
* @var string
* Relative template path
*/
$templatePath = null === $this->basePath ?
$templateName : "{$this->basePath}/{$templateName}";
// Start the buffer
ob_start();
// Load the template
require $templatePath;
// Return the template content
return ob_get_clean();
}
public function createTemplate(string $html, string $templateName)
{
/**
* @var string relative template path
*/
$templatePath = "{$this->basePath}/{$templateName}";
$safeHtml = $this->cleaner->cleanTags($html, ["script"]);
file_put_contents($templatePath, trim($safeHtml));
}
/**
* Insert an html string inside a template
* The twig template file will be created or updated
*/
public function createTemplateFrom(string $baseTemplateName, string $targetTemplateName, string $html): void
{
$baseHtml = $this->render($baseTemplateName);
$newHtml = str_replace($this->identifier, $html, $baseHtml);
$this->createTemplate($newHtml, $targetTemplateName);
}
/**
* Transforms an html string with brackets
* into a twig string with mustaches
*
* @param string $html
* @return string
*/
private function htmlToTwig(string $html) : string
{
// Search for brackets
$pattern = "/\[(\S*)\]/s";
// Replace brackets by mustaches
$twig = preg_replace($pattern, '{{ ${1} }}', $html);
return $twig;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment