Skip to content

Liquid for programmers

harrydeluxe edited this page May 13, 2012 · 5 revisions

Extending Liquid

Extending Liquid is very easy. However, keep in mind that Liquid is a young library and requires some outside help. If you create useful filters and tags, please consider creating a patch and attaching it to a ticket here on this trac.

Create your own tag blocks

All tag blocks are parsed by Liquid. To create a new block, you just have to inherit from LiquidBlock and register your block with LiquidTemplate.

class LiquidTagNodisplay extends LiquidBlock
{
    public function render(&$context)
    {
        return '';
    }
}
$text = " {% nodisplay %} don't show me! {% endnodisplay %} ";
$liquid = new LiquidTemplate();
$liquid->registerTag('nodisplay', 'LiquidTagNodisplay');
$liquid->parse($text);
echo $liquid->render();  // => ""

Create your own filters

Creating filters is very easy. Basically, they are just methods which take one parameter and return a modified string. You can use your own filters by passing an array of modules to the render call like this: $liquid->registerFilter(new SiteFilter());.

class SiteFilter
{
    public function stylesheet($file, $media = 'sreen')
    {
        $files = explode(',', $file);
        $media = isset($media) ? ' media="'.$media.'"' : '';
        $r = '';

        foreach($files as $link)
            $r .= '<link href="/theme/default/stylesheets/'.trim($link).'.css"'.$media.' rel="stylesheet" type="text/css" />'."\n";
        return $r;
    }
}

Now you can use the filter 'stylesheet' in your templates.

{{ 'master' | stylesheet }}
{{ 'blog,content' | stylesheet: 'print' }}

And this is the result:

<link href="/theme/default/stylesheets/master.css" media="sreen" rel="stylesheet" type="text/css" />
<link href="/theme/default/stylesheets/blog.css" media="print" rel="stylesheet" type="text/css" />
<link href="/theme/default/stylesheets/content.css" media="print" rel="stylesheet" type="text/css" />
Clone this wiki locally