If you want a global variable / object in Twig, you have to implement Twig_Extension
and add a new global (which will be accessible to all your templates).
A simple example would be:
1) Register a service in <bundle>/Resources/config/services.yml
services:
acme.twig.acme_extension:
class: Acme\DemoBundle\Twig\AcmeExtension
tags:
- { name: twig.extension }
2) Then create the extension:
<?php
namespace Acme\DemoBundle\Twig
class AcmeExtension extends \Twig_Extension {
public function getGlobals() {
return [
'menu' => new Menu(),
];
}
}
3) Then in your template:
{{ menu.render }} // Whatever
Of course, you can pass arguments to the Twig extension if needed.
Anyway, if you're trying to build a menu, maybe you should have a look at KnpMenuBundle, which helps a lot (https://github.com/KnpLabs/KnpMenuBundle)
Hope it helps!