feulf/raintpl

PHP 5.3 Closures

Closed this issue · 4 comments

I'm wondering what kind of neat magic could be done by combining PHP 5.3 Closures with your RainTPL templating.

<?php
$table = new RainTPL;
$table->assign('posts', $this->posts)
    ->column('Post', function($item, $view) { return $item->title; })
    ->column('Status', function($item, $view) { return $item->status; })
    ->column('Date Published', function($item, $view) {
        return ($item->date_published) ? $view->dateFormat($item->date_published) : '(Unpublished)'; 
    });
$table = $table->draw( 'post.table',  true);
?>

Anonymous function are definitely one of the coolest new features of php 5.3!

I'm OK with the idea to use PHP 5.3 feature on RainTPL , and by the way we already thinking about rewrite the entire template engine in 5.3, but we don't want to change too much, because the purpose it's just to have an easy and readable separation of logic by presentation.

I sincerely don't understand very well how your code could work, I think you mean to add a column method to the Raintpl class right? Could you explain it please?

The idea in that article is that you could create anonymous functions that are run on each item in the group (or table) to give it custom formatting. For example, if you had an admin area with a bunch of posts to approve you could assign them to the template.

$table->assign('posts', $this->posts);

And then pass some functions to run on each column of the $this->posts[x]->date_published.

$table->column('date_published', function($item, $view) 
{
    return ($item->date_published) ? $view->dateFormat($item->date_published) : '(Unpublished)'; 
});

So you can specify how you want that column to print out WITHOUT having to embed that logic in the view.

That's interesting, anyway how could you print each column in the template, just {$table.post}?

Xeoncross, check RainTpl 3, we implemented the closure function for register new tags.