Skip to content
brunobraga edited this page Sep 25, 2012 · 11 revisions

Filters

Single filter


<?php
require 'h2o/h2o.php';
$user = array('name'=>'peter', 'email'=> '[email protected]');
echo h2o('{{ user.email | avator | image_tag')->render(compact('user'));
?>

h2o::addFilter('avator');
function avator($email) {
    return "http://gravator.com/api?email=".md5($email);
}
?>

Filter collections

If you have a lot of related filters for your application, putting them into a filter collection class can give you better encapsulation and reuse on your methods.

Here is some code example of a Filter collection class, h2o::addFilter() is a static method overloading a few different parameter options, if you pass-in a filter collection then all class methods will become h2o filters.


<?php
  h2o::addFilter('HtmlFilters');
  class HtmlFilters extends FilterCollection {
     function base_url($url) {
        return $url;
     }
     static function script_tag($path) {
        return sprintf('<script type="text/javascript" src="%s.js">', self::base_url($path));
     }
     ...
  }
?>

Tags

Tags are powerful stuff, creating a new tag allows you to

  • interact with h2o context and parser objects
  • implement new language construct, template macros
  • consuming external resources

This is favorite example of implementing a rss feed loader tag less than 20 lines with object caching


<?php
require 'h2o/h2o.php'

class Load_feed_items_Tag extends H2o_Node {
    var $url, $cacheKey;

    function __construct($argstring, $parser, $pos=0) {
        $this->url = trim($argstring);
        $this->cacheKey = md5($this->url);
    }

    function render($context, $stream) {
        $cache = h2o_cache($context->options);

        # try cached 
        if (! ($feed = $cache->read($this->cacheKey))) {
            $feed = file_get_contents($this->url);
            $cache->write($this->cacheKey, $feed);
        }
        $feed = simplexml_load_string($feed)->xpath('//channel/item');
        $context->set('feed_items', $feed);
    }
}

h2o::addTag('load_feed_items');

# Template part
$tpl = <<<TPL
    {% load_feed_items http://feeds.digg.com/digg/popular.rss %}
    {% for item in feed_items %}
        {{ item.title | links_to item.url }}
     {% endfor %}
TPL;

echo h2o($tpl)->render();

Extensions