Yii 2 Integration Guide

How to integrate Tplix with Yii 2 using a custom Component class registered in the application config

Yii · v2.x

Tplix + Yii 2

Register a Tplix component in the application config and use it from any controller via Yii::$app->tplix.

composer require tplix/tplix
1

Create the Component

components/TplixComponent.php
<?php
namespace app\components;

use Tplix\Tplix;
use yii\base\Component;

class TplixComponent extends Component
{
    public string $templateDir = '';
    public string $compileDir  = '';
    public string $cacheDir    = '';
    private Tplix $tpl;

    public function init(): void
    {
        parent::init();
        $this->tpl = Tplix::getInstance();
        $this->tpl->setTemplateDir(\Yii::getAlias($this->templateDir));
        $this->tpl->setCompileDir(\Yii::getAlias($this->compileDir));
        $this->tpl->setCacheDir(\Yii::getAlias($this->cacheDir));
    }

    public function render(string $template, array $vars = []): string
    {
        $this->tpl->assign($vars);
        return $this->tpl->fetch($template);
    }
}
2

Register in Application Config

config/web.php
'components' => [
    'tplix' => [
        'class'       => 'app\components\TplixComponent',
        'templateDir' => '@app/views/tplix',
        'compileDir'  => '@runtime/tplix_c',
        'cacheDir'    => '@runtime/tplix_cache',
    ],
],
3

Use in a Controller

controllers/SiteController.php
public function actionIndex(): string
{
    return \Yii::$app->tplix->render('site/index.tpl', [
        'title' => 'Home',
        'user'  => \Yii::$app->user->identity,
    ]);
}