Tutorial :What's the difference between Partial and Slot in Symfony?



Question:

The two concepts Partial and Slot seem the same for me. Both of these two features replace placeholders in template with actual markup.

When should I use Partial and when should I use Slot?


Solution:1

The major difference between slots and partials is that the rendering for a given slot resides within a certain template. In opposite, the partial is merely an include of a template into another template.

"Basically, a slot is a placeholder that you can put in any of the view elements (in the layout, a template, or a partial). Filling this placeholder is just like setting a variable. The filling code is stored globally in the response, so you can define it anywhere (in the layout, a template, or a partial). Just make sure to define a slot before including it, and remember that the layout is executed after the template (this is the decoration process), and the partials are executed when they are called in a template."

Examples of ways of using each are:

  • Title for your page - would probably be placed in a slot (or in the title helper), and you would then in your layout check whether the slot was defined and then show it.
  • Sidebar items - say you have 3 sidebar "slots", you would then have three slots, for example 'sidebar-1', 'sidebar-2' and 'sidebar-3'. In your template you would then define the slot, which could be rendered using a partial (or even a component) if you wanted.

I hope that clarified it a bit.


Solution:2

A partial comes from a file:

include_partial('thing', $params) will include _thing.php with $params in it's scope.

Slots are not files, but set somewhere else in the template/controller:

slot('title', 'Home Page');
echo '<title>'.slot('title').'</title>'


Solution:3

All you need to know is the Symfony cheat sheet View. Partials, components, slots and component slots (PDF, 45 KB).


Solution:4

You could think of a slot as an OO method definition. Your layout defines slots. The template extends the layout and fills those slots (by overwriting the methods). You can also have a default content for a slot, which is displayed when it's not overwritten.

Partials on the other hand would be like composition. They are a reusable component that templates can access. Roughly they are the equivalent of a simple include statement, but you pass in the variables it uses.

This page does a pretty good job at explaining the concepts: http://www.symfony-project.org/book/1_2/07-Inside-the-View-Layer


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »