Partials in lithium

lithium, partials, php, templates, view

Solution

Why using plugins when this stuff can hopefully be done by Lithium :-)

I don't know Zend, but here is an exemple to configure elements default paths differently, to load them from the related view folder, instead of a shared path.

And let's add one more thing: we want to differentiate elements/partials from a normal view, by appending un underscore to the name of the file (mimic Rails partials)

First, reconfigure Media during the bootstrap process (config/bootstrap/media.php)

Media::type('default', null, array(
    'view' => 'lithium\template\View',
    'paths' => array(
        'layout' => '{:library}/views/layouts/{:layout}.{:type}.php',
        'template' => '{:library}/views/{:controller}/{:template}.{:type}.php',
        'element'  => array(
            '{:library}/views/{:controller}/_{:template}.{:type}.php',
            '{:library}/views/elements/{:template}.{:type}.php'
        )
    )
));

Then, use it

Suppose a controller `Documents`. Call on a view:

<?= $this->_render('element', 'foo', $data, array('controller' => 'documents')); ?>

This will look for a file inside `views/documents/_foo.html.php` and if doesn't exists, fallback to `/views/elements/foo.html.php`

This kind of simple re-configuration of framework defaults, can be done in Lithium for a bunch of stuffs (default controllers paths to create namespaces, views paths, libraries, etc ...)

One more example to re-maps your template paths so you can have stuff like `pages/users_{username}.php` instead of the Lithium default: https://gist.github.com/1854561

Problem

Normally I use the Zend Framework and this is something I miss in Lithium. Partials. There is a render method in the view where you can use 'elements' which is the closest I got. ``` <?php $this->_render('element', 'form); ?> ``` This does work, however it requires that the form.html.php file is in the /views/elements folder. Is it possible to let it search in another path? Like /views/users/ so it gets the file /views/users/form.html.php. I have tried the following, since I found out that the render method does accept an options argument wherein you can specify a path. So I made an Helper to fix this problem for me. ``` namespace app\extensions\helper; use lithium\template\TemplateException; class Partial extends \lithium\template\Helper { public function render($name, $folder = 'elements', $data = array()) { $path = LITHIUM_APP_PATH . '/views/' . $folder; $options['paths']['element'] = '{:library}/views/' . $folder . '/{:template}.{:type}.php'; return $this->_context->view()->render( array('element' => $name), $data, $options ); } } ``` However it still only searches in the /view/elements folder, not in the path I specified. Is there something I am doing wrong?

Original source