I want to create a simple twig extension ({{imgWidth(...)}}) that calls getimagesize() and returns the width and height of an image on the server.
I followed the instuctions you can find here.
When I reload my page I only can see a blank page - the error.log tells me that
PHP Fatal error: Class 'Fms\MediaBundle\Twig\Extension\ImgsizeExtension' not found in /var/www/fms/app/cache/dev/appDevDebugProjectContainer.php on line 4773
The service in MediaBundle\Resources\config\services.yml looks like:
services:
twig.extension.imgsize:
class: Fms\MediaBundle\Twig\Extension\ImgsizeExtension
tags:
- name: twig.extension
The class is:
<?
// src/Fms/MediaBundle/Twig/Extension/ImgsizeExtension.php
namespace Fms\MediaBundle\Twig\Extension;
class ImgsizeExtension extends \Twig_Extension
{
public function getFunctions()
{
return array(
new \Twig_SimpleFunction('imgsize', array($this, 'imgWidth'))
);
}
public function imgWidth($mediaId = 0, $mediaSize = 'L')
{
// ...
return $mediaId;
}
public function getName()
{
return 'imgsize';
}
}
Clearing cache via console or manually didnt help too.
Change <? to <?php. I copied your code and in with this modification symfony finally finds this class.
Related
I'm adding a custom twig extension service to a Drupal 8 module. My services file looks like this:
services:
analytics.my_twig_extension:
class: Drupal\analytics\TwigExtension\MyTwigExtension
tags:
- { name: twig.extension }
I get this error when running drush cr:
[warning] Drush command terminated abnormally. Check for an exit()
in your Drupal site.
When I remove the tags property in services file, like this:
services:
analytics.my_twig_extension:
class: Drupal\analytics\TwigExtension\MyTwigExtension
then drush cr works correctly, but my Twig extension functions are not not running at all.
The MyTwigExtension class:
<?php
namespace Drupal\analytics\TwigExtension;
use Twig_Extension;
use Twig_SimpleFilter;
class MyTwigExtension extends \TwigExtension {
public function __construct() {
}
public function getFunctions() {
return [
new \Twig_SimpleFunction('get_type', array($this, 'getType'))
];
}
public function getType($var) {
return gettype($var);
}
}
?>
Does anyone have any idea why this is happening?
Jacob, you're a dummy.
I fixed it by simply using extends \Twig_Extension instead of extends \TwigExtension. A coworker found the answer. Unfortunately, there was no indication in the logs that this was the problem.
I am new with Symfony and I've searched a lot on the net how to use core PHP functions like array functions (in_array , array_combine) , string functions (strpos , strlen) , date functions (date,timestamp),etc.. In Symfony Twig file?
Firstly, create Twig/Extension directory into your bundle. Sample: AppBundle/Twig/Extension
Then, create a class for your function name. I create a JsonDecode and i use every twig file this function;
namespace AppBundle\Twig\Extension;
class JsonDecode extends \Twig_Extension {
public function getName() {
return 'twig.json_decode';
}
public function getFilters() {
return array(
'json_decode' => new \Twig_Filter_Method($this, 'jsonDecode')
);
}
public function jsonDecode($string) {
return json_decode($string);
}
}
Then,
add lines into services.yml;
twig.json_decode:
class: AppBundle\Twig\Extension\JsonDecode
tags:
- { twig.extension }
that's enough.
You have to create a custom twig extension that you could use in your twig template.
You can follow the symfony documentation
what I am trying to do is to have custom error page, not only will they be extending the base layout but also I want extra up selling content in those pages too so changing templates only is not an option
regardless of the reason (404 Not Found or just missing variable) I would like to show my template and my content instead
I have spent hours trying to get this going with no luck
app/console --version
Symfony version 2.5.6 - app/dev/debug
I tried some resources, but couldn't get it working. The name a few:
http://symfony.com/doc/current/reference/configuration/twig.html
http://symfony.com/doc/current/cookbook/controller/error_pages.html
I'm running in dev with no debug, see app_dev.php below:
$kernel = new AppKernel('dev', false);
following the tutorials i got these extra bits
app/config/config.yml
twig:
exception_controller: SomethingAppBundle:Exception:show
in my bundle
<?php
namespace Something\AppBundle\Controller;
use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
use Symfony\Component\HttpKernel\Exception\FlattenException;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class ExceptionController extends Controller
{
public function showAction( FlattenException $error, DebugLoggerInterface $debug)
{
print_r($error);
}
}
but my error controller does not get executed,
I am on purpose causing error by trying to echo undefined variable in different controller, since it should handle error from entire application
At the beginning you need to create action in the controller:
<?php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class ErrorController extends Controller
{
public function notFoundAction()
{
return $this->render('error/404.html.twig');
}
}
Then you need to create a Listener:
<?php
namespace AppBundle\EventListener;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\HttpKernelInterface;
class NotFoundHttpExceptionListener
{
private $controller_resolver;
private $request_stack;
private $http_kernel;
public function __construct($controller_resolver, $request_stack, $http_kernel)
{
$this->controller_resolver = $controller_resolver;
$this->request_stack = $request_stack;
$this->http_kernel = $http_kernel;
}
public function onKernelException(GetResponseForExceptionEvent $event)
{
if ($event->getException() instanceof NotFoundHttpException) {
$request = new \Symfony\Component\HttpFoundation\Request();
$request->attributes->set('_controller', 'AppBundle:Error:notFound');
$controller = $this->controller_resolver->getController($request);
$path['_controller'] = $controller;
$subRequest = $this->request_stack->getCurrentRequest()->duplicate(array(), null, $path);
$event->setResponse($this->http_kernel->handle($subRequest, HttpKernelInterface::MASTER_REQUEST)); // Simulating "forward" in order to preserve the "Not Found URL"
}
}
}
Now register the service:
#AppBundle/Resources/config/services.yml
services:
kernel.listener.notFoundHttpException:
class: AppBundle\EventListener\NotFoundHttpExceptionListener
tags:
- { name: kernel.event_listener, event: kernel.exception, method: onKernelException, priority: -10 }
arguments: [ #controller_resolver, #request_stack, #http_kernel ]
Not tested this, but rather it should work;)
EDIT:
Tested, it works. On the rendered page, you have a session, so you have access to app.user, his cart, and other matters related to the session.
I need to populate a variable with some HTML code and make it available to my base.html.twig file.
To achive this I have made a twig extension. This is my first time using twig extentions so im not sure if this is the correct way of doing things.
Here is what I have so far:
Extension code:
class GlobalFooterExtension extends \Twig_Extension
{
public function getFilters()
{
return array(
new \Twig_Filter_Function('GlobalFooter', array($this, 'GlobalFooter')),
);
}
public function GlobalFooter()
{
$GlobalFooter = file_get_contents('http://mysite.co.uk/footer/footer.html.twig');
return $GlobalFooter;
}
public function getName()
{
return 'GlobalFooter_extention';
}
}
config.yml:
services:
imagine.twig.GlobalFooterExtension:
class: Imagine\GdmBundle\Twig\GlobalFooterExtension
tags:
- { name: twig.extension }
base.html.twig:
{{GlobalFooter}}
This give the following error:
Twig_Error_Runtime: Variable "GlobalFooter" does not exist in "ImagineGdmBundle:Default:product.html.twig" at line 2
Im sure im missing something really obvious. How do I make $GlobalFooter from my GlobalFooterExtension class available to my base.hmtl.twig file?
You want to set a global variable, not a function.
Just use getGlobals and return your variable:
class GlobalFooterExtension extends \Twig_Extension
{
public function getGlobals()
{
return array(
"GlobalFooter" => file_get_contents('http://mysite.co.uk/footer/footer.html.twig'),
);
}
public function getName()
{
return 'GlobalFooter_extention';
}
}
Or, if you want to lazy load the value of the variable, create a function and change your template to:
{{ GlobalFooter() }}
Besides this, if the footer file is on the same site, it's better to use the {% include '...' %} tag.
rename function getFilters to getFunctions
I want to add my own twig functionality and to add new twig extension in Symfony 2.
To do that i created these folders: src/Ptracker/TasksBundle/Twig and src/Ptracker/TasksBundle/Twig/Extension and put file myTwigExtension.php in it with this content:
<?php
namespace Ptracker\TasksBundle\Twig\Extension;
class MyTwigExtension extends \Twig_Extension {
public function getFilters() {
return array(
'var_dump' => new \Twig_Filter_Function('var_dump'),
'linkable' => new \Twig_Filter_Method($this, 'linkable'),
);
}
public function linkable($sentence, $expr) {
return 'it works!!';
}
public function getName()
{
return 'my_twig_extension';
}
}
?>
Also i added some code to src/Ptracker/TasksBundle/Resources/config/services.yml :
services:
ptracker.twig.extension:
class: Ptracker\TasksBundle\Twig\Extension\MyTwigExtension
tags:
- { name: twig.extension }
The point is that i ALWAYS get the same fatal error:
Fatal error: Class 'Ptracker\TasksBundle\Twig\Extension\MyTwigExtension' not found in /home/renat/www/ptracker/app/cache/dev/appDevDebugProjectContainer.php on line 1092
What am i doing wrong? I've spent several ours to fix this problem, tried to put extension file in different folders, changed namespace.. nothing helps.
Please help me :)
File names are case-sensitive on linux and it doesn't find anything because it tries to load ../MyTwigExtension.php. Rename your file to MyTwigExtension.php.