Notizen zu einer exemplarischen Twig Extension unter ZF2 &ZfcTwig:
Klasse anlegen z.B. unter Application/src/Application/View/CustomTwigExtension.php
<?php // http://stackoverflow.com/questions/28254666/twig-add-filter namespace Application\View; use Twig_Extension; use Twig_SimpleFilter; use Twig_SimpleFunction; class CustomTwigExtension extends Twig_Extension { public function getFilters() { return [new Twig_SimpleFilter('ucfirst', 'ucfirst') ]; } public function getName() { return "CustomTwigExtension"; } public function getFunctions() { return [new Twig_SimpleFunction('renderimg', function ($picture, $width = 100, $height = 100) { $filename = basename($picture); return '<img src="' . $filename . '" width="' . $width . '" height="' . $height . '" />'; } , array( 'is_safe' => array( 'html' ) )) ]; } }
Custom Extension in config/autoload/global.php registieren:
<?php /** * Global Configuration Override * * You can use this file for overriding configuration values from modules, etc. * You would place values in here that are agnostic to the environment and not * sensitive to security. * * @NOTE: In practice, this file will typically be INCLUDED in your source * control, so do not include passwords or other sensitive information in this * file. */ return array( 'zfctwig' => [ 'extensions' => [ 'Twig_Extension_Debug', // Custom Twig Extension registrieren \Application\View\CustomTwigExtension::class, ], 'environment_options' => array( 'debug' => false ) ], );
Verwendung im Twig Template
{{ renderimg('test.jpg', 100, 100) }}