pug-php / pug-symfony

Pug (Jade) template engine for Symfony

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Adding custom helper

NotJustPizza opened this issue · comments

How can I add https://github.com/Gregwar/ImageBundle with image() helper to pug?

commented

In the future, pug will use the native twig adapter to get everything that works in twig to works in pug too.

For now, you can:

  1. create global function, if you include helpers.php with:
use Gregwar\ImageBundle\ImageHandler;

function image($originalFile = null, $width = null, $height = null, $throwException = null, $fallbackImage = null) {
  return new ImageHandler($originalFile, $width, $height, $throwException, $fallbackImage);
}

in it, then you can use image() in your pug template, the same goes far all functions, global pattern is a poor pattern but it do the trick quickly.

  1. provide functions from your controller:
// In some config global place, base controller setup or something
$pug = $this->get('templating.engine.pug');
// replace $this with $kernel->getContainer() if you call it from a place you can only access the kernel
$imageBundle = $this->get('image.handling'); // Get your service the same way
$pug->getEngine()->share([
  'image' => function ($source) use ($imageBundle) {
    return $imageBundle->open($source);
  },
]);

This allow you to call $image as a closure in your templates:

img(src=$image('foobar.png')->rotate(90))

It's very usefull. Thank you for your answer!