Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load a controller function and render it in a twig tag using Symfony2?

Tags:

I am using Symfony2 and Twig. I have a function (below) in my controller that returns a specific text. Is it possible to call that function directly from my template and change the {{text}} in my template to whatever the function returns, possibly via Ajax?

Here's my function:

public function generateCode($url) {
    $url = $_SERVER['SERVER_NAME'] . '/embed/' . $url;
    $return = '<iframe>'.$url.'</iframe>';
    return $return;
}

Another controller function calls the function above and renders my template:

public function getCodeAction($url) {
    $text = $this->generateCode($url);
    return $this->render('MyMyBundle:User:code.html.twig', array('text' => $text));
}

In my template I am using:

{{ text }}

to display the value.

like image 621
Mike Avatar asked Nov 27 '11 22:11

Mike


3 Answers

In Symfony 2.2, this was changed.

The render tag signature and arguments changed.

Before:

{% render 'BlogBundle:Post:list' with { 'limit': 2 }, { 'alt': BlogBundle:Post:error' } %}

After:

{% render controller('BlogBundle:Post:list', { 'limit': 2 }), { 'alt': 'BlogBundle:Post:error' } %}

or

{{ render(controller('BlogBundle:Post:list', { 'limit': 2 }), { 'alt': 'BlogBundle:Post:error'}) }}

Note: The function is the preferred way.

See https://github.com/symfony/symfony/blob/2.2/UPGRADE-2.2.md

like image 136
Dan Blows Avatar answered Nov 03 '22 01:11

Dan Blows


You can use ajax if you have dynamic data, but as far as I can see from your brief info, you can always execute that controller function directly from your view:

{% render "MyMyBundle:User:generateCode" with { 'url': 'your url here' } %}

More Information on this available at: http://symfony.com/doc/2.0/quick_tour/the_view.html, under Embedding other Controllers

like image 20
Stelian Avatar answered Nov 02 '22 23:11

Stelian


For the record, in new versions you need to use the absolute URL:

{{ render url('my_route_id', {'param': value}) }}
like image 24
Mateo Tibaquira Avatar answered Nov 02 '22 23:11

Mateo Tibaquira