Skip to content

Instantly share code, notes, and snippets.

@matej21
Created September 25, 2013 00:37
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 matej21/6693372 to your computer and use it in GitHub Desktop.
Save matej21/6693372 to your computer and use it in GitHub Desktop.
<?php
use Nette\Application\UI\Presenter;
class TemplateFactory extends \Nette\Object
{
/**
* @var \Nette\DI\Container
*/
protected $container;
protected $helperLoaders = array();
protected $helpers = array();
public function __construct(\Nette\DI\Container $container)
{
$this->container = $container;
$this->addHelperLoader('Nette\Templating\Helpers::loader');
}
public function addHelperLoader($callback)
{
$this->helperLoaders[] = $callback;
}
public function addHelper($name, $callback)
{
$this->helpers[$name] = $callback;
}
/**
* @param string|NULL
* @return \Nette\Templating\ITemplate
*/
public function createTemplate($control = NULL, $class = NULL)
{
$template = $class ? new $class : new \Nette\Templating\FileTemplate;
$template->onPrepareFilters[] = $this->templatePrepareFilters;
foreach ($this->helperLoaders as $callback) {
$template->registerHelperLoader($callback);
}
foreach ($this->helpers as $helper => $callback) {
$template->registerHelper($helper, $callback);
}
$template->netteHttpResponse = $this->container->getByType('Nette\Http\IResponse');
$template->netteCacheStorage = $this->container->getByType('Nette\Caching\IStorage');
$template->baseUri = $template->baseUrl = rtrim($this->container->getByType('Nette\Http\IRequest')->getUrl()->getBaseUrl(), '/');
$template->basePath = preg_replace('#https?://[^/]+#A', '', $template->baseUrl);
$template->user = $this->container->getByType('Nette\Security\User');
if ($control) {
$presenter = $control->getPresenter(FALSE);
// default parameters
$template->control = $template->_control = $control;
$template->presenter = $template->_presenter = $presenter;
if ($presenter instanceof Presenter) {
$template->user = $presenter->getUser();
// flash message
if ($presenter->hasFlashSession()) {
$id = $control->getParameterId('flash');
$template->flashes = $presenter->getFlashSession()->$id;
}
}
if (!isset($template->flashes) || !is_array($template->flashes)) {
$template->flashes = array();
}
}
$template->setCacheStorage($this->container->{"nette.templateCacheStorage"});
return $template;
}
public function templatePrepareFilters($template)
{
$template->registerFilter($latte = $this->container->createService('nette.latte'));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment