Wrzasq.pl

Symfony2 - global templating variables in PHP renderer with ChillDevViewHelpersBundle

Thursday, 16 June 2016, 10:47

Short time ago, while working on one of my projects i faced a problem with PHP templating engine in Symfony2 (again the same) - passing pre-defined variables to view renderer. For some reason it's not possible to define global variables for PHP templating engine. It is possible for Twig (with TwigBundle), but there is no equivalent of that for PHP. After googling for a moment and browsing some of Stack Overflow questions I ensured myself that it's not possible and that I'm not the only one who is looking for such a feature.

Solution

So, as a developer of ChillDevViewHelpersBundle I decided to implement and share the solution on my own. The feature of defining global variables exists on itself in PHP renderer in Symfony2 templating component - it's just not possible to define these variables in your application configuration, which is usually what people want. Unfortunately, you can't access and modify services definitions from outside your DI extension scope. The way I've done that is by using DI compiler pass then to post-process the DI container.

Values

Basic usage is to pass simple values into templates simply with a key-value map in your application configuration:

chilldev_viewhelpers:
    globals:
        values:
            someVariable: "your value"
            smsCode: "IKNC1M"

Viola! It's now there, in your templates:

<p>you should see <?php echo $someVariable; ?></p>

Services

In a very similar way you can also publish DI services to your templates:

chilldev_viewhelpers:
    globals:
        services:
            someVariable: "some.service.id"
            validator: "validator"

And the very same way like with plain values, these services are now available in all PHP templates:

<p><?php echo $someVariable->someMethod(); ?></p>

Yup, that's all, just that! Enjoy ChillDevViewHelpersBundle 0.1.8.

Tags: , , ,