Poorman
Poorman

Reputation: 205

Extend Twig with variables

I use Twig and I have a header in each file with some variables. How I can include the header in each file without always calling the variables ?

I've a file, in it, I extends the layout.html.twig and in this layout I extends the header.html.twig

on the header I've some variables sent by the controller. but the variables are executed only if I go to the header view...

How can I do to include the header view with twig?

Upvotes: 1

Views: 866

Answers (1)

b.b3rn4rd
b.b3rn4rd

Reputation: 8830

Despite the fact that is really difficult to understand what exactly you're after, probably, you're looking for a way to set global variables.

Twig globals allows you to set global variables.

Set static variables:

# app/config/config.yml
twig:
    # ...
    globals:
        variables: {}

If you need more than static variables, create your own extension:

<?php
namespace Example\CommonBundle\Twig;
use \Doctrine\ORM\EntityRepository;

class TooltipsExtension extends \Twig_Extension
{
    protected $bookingsTooltip;

    public function __construct(EntityRepository $bookingsTooltip)
    {
        $this->bookingsTooltip = $bookingsTooltip;
    }

    public function getGlobals()
    {
        return array(
            'tooltips' => $this->bookingsTooltip->getTooltips(),
        );
    }

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

Register twig extension:

# app/config/services.yml
example.tooltips_extension:
    class: Example\CommonBundle\Twig\TooltipsExtension
    public: false
    arguments:
        - @example.tooltips
    tags:
        - { name: twig.extension }

Access variables inside your html:

{{ dump(tooltips) }}

Upvotes: 1

Related Questions