My friends and family are under attack in Ukraine. Donate to protect them directly or help international organizations.

Symfony – subfolders for partials

February 19th, 2011

Symfony 1.2 – 1.4 expects all partials to follow this convention: templates/_partial.php

What happens when you need to organize your partials in subfolder? I tried a number of "Symfunky" avenues. Feel free to skip to the solution.

Avenues Explored

I first try the call the include_partial helper with "subfolder/partial", but that results in Symfony attempting to find the partial in the "subfolder" module.

Alright, so I try "module/subfolder/partial", but that results in Symfony looking for "_subfolder/partial" because it simply split at the first backslash. I don't blame the framework developers: I am trying to do something it was not meant to do.

So now I realize that we can set any template from an action using $this->setTemplate(‘subfolder/_partial'). Since actions are NOT partials by definition, I decide to use a component. Unfortunately the component doesn't allow the developer to override templates.

I am starting to feel that the framework mocks me. So this is how you wanna play it, huh? I will override your sfView class, load it in factories.yml, and there's nothing you can do about it (insert diabolical laughter)! But then, after almost half an hour, I realize that I'm trying to make it too elegant for something so basic as concatenating a few strings.

Solution

The solution ended up ridiculously simple and does not risk breaking any existing code.

1. Copy get_partial() helper with an extra param: get_partial_subfolder($templateName, $vars = array(), $subfolder)
2. Edit the line that concatenates the file name: $actionName = $subfolder.'/_'.$templateName; (instead of ‘_'.$templateName)

There you go, no more headaches. Just remember to use "echo get_partial()" instead of "include_partial()" unless you want to override that helper as well. If you are unsure how to create custom helpers, see here under Adding Your Own Helpers: http://www.symfony-project.org/book/1_2/07-Inside-the-View-Layer

Previous: SVG Transparent Color in Firefox Next: Integrating Markdown with Symfony