Skip to content

Instantly share code, notes, and snippets.

@matperez
Last active October 22, 2021 20:20
Show Gist options
  • Select an option

  • Save matperez/ea2eaf16abe9329d5147 to your computer and use it in GitHub Desktop.

Select an option

Save matperez/ea2eaf16abe9329d5147 to your computer and use it in GitHub Desktop.
Render twig templates from string
<?php
use app\components\twig\TwigRenderer;
$container = Yii::$container;
$container->setSingleton(TwigRenderer::class, TwigRenderer::class);
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace app\commands;
use app\components\twig\TwigRenderer;
use yii\console\Controller;
class DefaultController extends Controller
{
/**
* @var TwigRenderer
*/
protected $renderer;
public function __construct($id, $module, TwigRenderer $renderer, $config = [])
{
$this->renderer = $renderer;
parent::__construct($id, $module, $config);
}
public function actionIndex()
{
// output: 123 hello world!
echo $this->renderer->render('123 {{test}}', ['test' => 'hello world!']).PHP_EOL;
}
}
<?php
namespace app\components\twig;
use yii\base\Component;
use yii\base\InvalidConfigException;
use yii\twig\ViewRenderer;
class TwigRenderer extends Component
{
/**
* View renderer config
* @var array
*/
public $config = [
'class' => ViewRenderer::class,
'cachePath' => false,
'options' => [
'auto_reload' => true,
],
];
/**
* @var \Twig_Environment
*/
protected $twig;
/**
* @param mixed $template
* @param array $data
* @return string
* @throws \yii\base\InvalidConfigException
* @throws \Twig_Error_Loader When the template cannot be found
* @throws \Twig_Error_Syntax When an error occurred during compilation
*/
public function render($template, array $data = [])
{
try {
$template = $this->getTwig()->createTemplate($template);
} catch (\Twig_Error_Syntax $e) {
return sprintf('Unable to render a template: %s.', $e->getMessage());
}
return $template->render($data);
}
/**
* @return \Twig_Environment
* @throws InvalidConfigException if the configuration is invalid.
*/
public function getTwig()
{
if (!$this->twig) {
/** @var ViewRenderer $render */
$render = \Yii::createObject($this->createConfig());
/** @var \Twig_Environment $twig */
$twig = clone $render->twig;
$twig->setLoader(new \Twig_Loader_Chain());
$this->twig = $twig;
}
return $this->twig;
}
/**
* @return array
*/
protected function createConfig()
{
if (isset(\Yii::$app->getView()->renderers['twig'])) {
return array_merge(\Yii::$app->getView()->renderers['twig'], $this->config);
}
return $this->config;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment