Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get controller name in TWIG template

I am learning symfony2.3, and I am getting an error when I try to get controller name in twig template.

Controller:

namespace Acme\AdminBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class DefaultController extends Controller
{
    public function indexAction($name)
    {
        return $this->render('AcmeAdminBundle:Default:index.html.twig', array('name' => $name));
    }
}

In my TWIG template:

{% extends '::base.html.twig' %}
{% block body %}
 {{ app.request.get('_template').get('controller') }}
 Hello {{ name }}!!!
{% endblock %}

Output:

Impossible to invoke a method ("get") on a NULL variable ("") in AcmeAdminBundle:Default:index.html.twig at line 3 

I want output as "Default"

I am using symfony 2.3, I have also tried on symfony 2.1 but on both version generates the same error.

like image 521
Hardeep Pandya Avatar asked Jun 21 '13 11:06

Hardeep Pandya


1 Answers

use this line to display a controller name in twig:

{{ app.request.attributes.get("_controller") }}
like image 155
Shadman Avatar answered Sep 22 '22 09:09

Shadman