Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2, how to send parameter to all views?

Tags:

php

svn

symfony

I need to send a parameter to all my views (twig template) with Symfony2.

Each view extend a special view : base.html.twig, so I think I just need to send this parameter to this base view.

  • But how can I do that?

Here is the way I get this parameter in my php file:

$svn = File('.svn/entries');
$svnrev = $svn[3];

Which represents the number of current revision.

  • Is there a way to retrieve this variable in a .yml?
like image 576
Clément Andraud Avatar asked Dec 04 '25 14:12

Clément Andraud


1 Answers

You should register a global variable using a twig extension.

The class

// src/Acme/YourBundle/Twig/SvnExtension.php
namespace Acme\YourBundle\Twig;

class SvnExtension extends \Twig_Extension
{
    public function getGlobals()
    {
        // you might need to adapt the file path
        $svn = File('.svn/entries');

        return array(
            'svn_rev' => $svn[3]
        );
    }

    public function getName()
    {
        return 'svn_extension';
    }
}

The service definition

# i.e. app/config/config.yml 
services:
    acme.twig.svn_extension:
        class: Acme\DemoBundle\Twig\SvnExtension
        tags:
            - { name: twig.extension }

Accessing the variable

Now your variable is accessible in every twig template as usual:

{{ svn_rev }}

Further improvements would include:

  • getting the filename from a parameter or environment variable (if the svn repo is stored elsewhere)
  • caching the file using apc(u) / memcache / whatever for performance
  • add more svn info and turn the variable into an array itself ( svn.rev , svn.state , ... )
  • ...
like image 103
Nicolai Fröhlich Avatar answered Dec 06 '25 07:12

Nicolai Fröhlich