pamil
pamil

Reputation: 980

Some kind of always-done part of all controllers in Symfony2

I've got layout, something like that:

{# ... #}
{% render 'PamilGooglePlusBundle:Default:sidebar' %}
{# ... #}
{{ globalVariable }}

In PamilGooglePlusBundle:Default:sidebar I run 2 queries using DBAL whose generate me list of users and groups. I have function in sidebarAction() which gave me name of actual resource: group or user name. I want to use it in other part of template.

I got to some thoughts. I have to run this method each query and get its variable every time, how to do it? I mean some kind of controller method which is always done so I can get the variable.

Upvotes: 2

Views: 133

Answers (1)

pamil
pamil

Reputation: 980

I solved this problem! ;)

Simply, we make Twig extensions, register there init function with some parameters, use it in main template and values are register globals - just like in this code:

<?php

namespace Pamil\GooglePlusBundle\Extension\Twig;

use Doctrine\DBAL\Connection;

class Sidebar extends \Twig_Extension
{
    private $dbal;

    private $init = false;

    public $data = array();

    // Specify parameters in services.yml
    public function __construct(Connection $dbal)
    {
        $this->dbal = $dbal;
    }

    public function sidebarInit($pathinfo)
    {
        // This function returns empty string only, cos you can use it only as 
        // {{ sidebarInit(app.request.info) }}, not in {% %}
        if ($this->init === true) {
            return '';
        }

        $this->data = $dbal->fetchAll("SELECT * FROM table");
        // for example:        
        $this->data['key'] = 'value';       

        $this->init = true;
        return '';
    }

    public function getFunctions()
    {
        return array(
                'sidebarInit' => new \Twig_Function_Method($this, 'sidebarInit'),
                );
    }

    public function getGlobals()
    {
        return array(
                'sidebar' => $this
                );
    }

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

Now the services.yml:

parameters:
    pamil.google.plus.bundle.extension.twig.sidebar.class: Pamil\GooglePlusBundle\Extension\Twig\Sidebar

services:
  pamil.google.plus.bundle.extension.twig.sidebar:
     class: "%pamil.google.plus.bundle.extension.twig.sidebar.class%"
     arguments: ["@database_connection"] #specify arguments (DBAL Connection here)
     tags:
            - { name: twig.extension, alias: ExtensionTwigSidebar }

And we can use it in template, for example main.html.twig:

{{ sidebarInit(app.request.pathinfo) }}
<html>
{# ... #}
{% include 'PamilGooglePlusBundle::sidebar.html.twig' %}

In sidebar.html.twig:

{{ sidebar.data.key }}
{# outputs 'value' #}

Hope it will help someone else ;)

Upvotes: 2

Related Questions