Installation
composer require yiisoft/yii2-twig
Ensure PHP ≥7.4 (PHP 8 recommended).
Basic Configuration
Add to config/web.php:
'view' => [
'renderers' => [
'twig' => [
'class' => 'yiisoft\yii2\twig\ViewRenderer',
'cachePath' => '@runtime/Twig/cache',
'viewPath' => '@app/views',
'options' => [
'auto_reload' => true, // For development
'cache' => false, // Disable caching in dev
],
],
],
],
First Use Case
Rename a view file from index.php to index.twig in your views directory.
Render it in a controller:
return $this->render('index', ['data' => $model]);
Ensure the renderer is set in the view file:
{% extends 'layout.twig' %}
{% block content %}
{{ dump(data) }}
{% endblock %}
View Rendering
{{ }}, {% %}) in .twig files.return $this->render('twig-view', ['key' => 'value']);
{{ key }} {# Outputs: value #}
Layouts and Extends
layout.twig):
<!DOCTYPE html>
{% block content %}{% endblock %}
{% extends 'layout.twig' %}
{% block content %}
<h1>Hello, Twig!</h1>
{% endblock %}
Partial Views (Includes)
{% include 'partials/header.twig' %}
{% include 'partials/user.twig' with {'name': 'John'} %}
Filters and Functions
{{ 'hello'|upper }}
config/web.php:
'view' => [
'renderers' => [
'twig' => [
'class' => 'yiisoft\yii2\twig\ViewRenderer',
'options' => [
'functions' => [
'my_func' => new \Twig\TwigFunction('my_func', function() { return 'custom!'; }),
],
],
],
],
],
{{ my_func() }}
Integration with Yii Helpers
Url, Html, etc., in Twig via yiisoft/yii2-twig-extensions:
{{ url('site/index') }}
{{ activeForm(['action' => url('site/contact')]) }}
Dynamic View Paths
Override getViewPath() in a custom ViewRenderer to load views from multiple locations:
class CustomViewRenderer extends ViewRenderer {
public function getViewPath($view) {
return [Yii::getAlias('@app/views'), Yii::getAlias('@vendor/views')];
}
}
Caching Strategies
'cache' => false).cachePath:
'options' => [
'cache' => true,
'cache_path' => '@runtime/Twig/cache',
],
rm -rf runtime/Twig/cache/*
Twig Extensions Create a custom Twig extension for reusable logic:
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
class MyTwigExtension extends AbstractExtension {
public function getFunctions() {
return [
new TwigFunction('greet', [$this, 'greetUser']),
];
}
public function greetUser($name) {
return "Hello, $name!";
}
}
Register in ViewRenderer:
'options' => [
'extensions' => [new MyTwigExtension()],
],
Error Handling Configure Twig to show errors in development:
'options' => [
'debug' => Yii::$app->environment === 'dev',
],
Customize error templates by setting error_handler in Twig options.
File Extensions
.php to .twig causes Yii to fall back to PHP rendering..twig.Caching in Development
'cache' => false and 'auto_reload' => true in dev.Namespace Conflicts
@app/modules/admin/views) may not resolve correctly.getViewPath() to include module paths.Yii Widgets in Twig
ActiveForm) require yiisoft/yii2-twig-extensions for compatibility.composer require yiisoft/yii2-twig-extensions
Autoloading Twig Extensions
autoload:dump).Enable Twig Debug Mode
Add to config/web.php:
'options' => [
'debug' => true, // Shows Twig errors in dev
],
Check Template Paths
Verify viewPath in config matches your actual view directory:
'viewPath' => [Yii::getAlias('@app/views'), '@vendor/views'],
Clear Runtime Cache If changes aren’t reflected, clear:
rm -rf runtime/Twig/cache/*
Twig Dump and Debug
Use Twig’s dump() for debugging:
{{ dump(variables) }}
Or enable strict_variables in options to catch undefined vars.
Custom View Renderer
Extend yiisoft\yii2\twig\ViewRenderer to modify behavior:
class CustomViewRenderer extends ViewRenderer {
public function render($view, $params = []) {
// Pre-process $params or $view
return parent::render($view, $params);
}
}
Twig Environment Configuration
Override createTwigEnvironment() to customize the Twig environment:
public function createTwigEnvironment() {
$loader = new \Twig\Loader\FilesystemLoader($this->getViewPath());
$options = $this->options;
$options['cache'] = Yii::$app->environment === 'prod' ? $options['cache_path'] : false;
return new \Twig\Environment($loader, $options);
}
Integrate with Yii Events
Listen to ViewRenderer::EVENT_BEFORE_RENDER to modify data before rendering:
Yii::$container->set(ViewRenderer::class, [
'class' => ViewRenderer::class,
'on beforeRender' => function($event) {
$event->sender->options['extensions'][] = new MyTwigExtension();
},
]);
Asset Management
Use Twig’s asset() function with Yii’s AssetBundle:
<link rel="stylesheet" href="{{ asset('@web/css/style.css') }}">
Ensure @web is configured in UrlManager.
How can I help you explore Laravel packages today?