Mar 05 2009

Passing variables from an action (or module template) to a layout template

Category: Variable ReferencingJeff @ 5:55 pm
      

Since Symfony 1.1, a bit of change has gone on with passing variables from an action to a layout file. You used to be able to do it like this:

$this->foo = 'bar';

And then you could call it in either your action’s template file or the application’s layout file like this:

<?php echo $bar ?>

But that’s no longer the case… for good reason, but I won’t get into that here.  Now you’re forced to use slots.  So If you want to use the same logic above, you must pass the variable via a slot in your action like this:

$this->getResponse()->setSlot('foo', 'bar');

Then you can call that variable value from within your layout template like this:

<?php echo get_slot('foo') ?>

You can also make the assignment from within your action’s template file like this:

<?php slot('foo', 'bar') ?>

And you’ll still call the variable the same way in your layout template.

9 Responses to “Passing variables from an action (or module template) to a layout template”

  1. CLC says:

    Perfect tip and perfect timing!

    Thanks

    Would be nice to know the “good reason” too

  2. StanN says:

    Does that work going the other way? Can I set in my templete and get in my Action?

  3. Ark says:

    $this->foo = ‘bar’;

    still works in symfony 1.2, don’t know what you mean.

  4. Jeff says:

    @Ark – It does work when you are assigning the variable from an action to that action’s corresponding template. However, it does not work when you are trying to make an assignment from an action to a layout template.

  5. WallTearer says:

    Thanks man, this stuff really works! =)

  6. Manuel says:

    thanks man!

    this safe a lot of time..!

  7. container says:

    omg, why is this not in the book !?!?!

    $this->getResponse()->setSlot(‘foo’, ‘bar’);

    searched for loads of time.

    checked now, and it is not even nowhere in Jobeet tutorial. This is bad, i think it is as intuitive to set slot contents (actually trans-view variables :) in controllers.

    Dammit, lost hours for this.

  8. sarimarton says:

    Joining to container. Lost hours for this. It should be in the Jobeet tutorial.

  9. adek23 says:

    This is not necessary to use slots, you can always do $this->getRequest()->setAttribute() in an action and then do $sf_request->getAttribute() in layout template.

Leave a Reply