On 6 Aug 2010, at 12:16, Bas Kooij wrote:

>> This is what prefilters are for:
>> class DateMagic extends PHPTAL_PreFilter 
>> {
>>  function filter($src) {return str_replace('[DATE]', '<span 
> tal:content="date | nothing" />', $src);}
>> }
>> $phptal->addPreFilter(new DateMagic());
> I tried usign PreFilters, but that doesn't seem work for inserted content, 
> only for code which is hard coded in the template. So if I retrieve the html 
> with the [DATE] tag from a database, insert it into a variable in my TAL 
> template, the PreFilter never fires for the [DATE] tag. If I put the [DATE] 
> tag in the template file itself it does work.

That's correct. PreFilter is run only once before template is executed for the 
first time, and result of PreFilter is cached by PHPTAL for all later runs of 
that template.

In PreFilters you're not supposed to replace your tags with data, but replace 
your tags with PHPTAL tags that will output desired data.

For example if you wanted [DATE] to insert current date, use PreFilter with:

str_replace('[DATE]', '<span tal:content="date | nothing" />', $src)

and then only update date variable:

$phptal->date = date('Y-m-d H:i:s');

This will give you tempalte that has [DATE] in it's source, and gives current 
date, updated every time.

> I have a working solution now. I have this in the home.xhtml template:
> <tal:block metal:use-macro="main.xhtml/main">
>     <tal:block metal:fill-slot="page">
>         <tal:block metal:use-macro="customMacro/customMacro" />
>     </tal:block>
> </tal:block>
> And I use the following SourceResolver:
> class MySourceResolver implements PHPTAL_SourceResolver {
>    public function resolve($path) {
>        if($path == 'homeMacro') {
>            $pageContent = [retrieve html with DATE tag from DB]
>            $content = '<tal:block metal:define-
> macro="customMacro">'.$pageContent.'</tal:block>';
>            $content = str_replace('[DATE]', '19-02-1981', $content);
>            return new PHPTAL_StringSource($content, 
> PHPTAL_StringSource::NO_PATH_PREFIX.md5($pageContent));
>        }
>    }
> }
> Is this the easiest/only way to achieve what I want?

You've reinvented prefilter here. It happens to work because md5($pageContent) 
forces to reload whole template whenever date changes (that's quite 

Even if you wanted template recompiled like that, you could do it with 

class DateMagic extends PHPTAL_PreFilter 
  function filter($src) {return str_replace('[DATE]', '19-02-1981' , $src);}
  function getCacheId() {return '19-02-1981';} // 

Do you want to allow your clients to use all PHPTAL constructs, or only HTML 
with your tags?

If the latter, then you don't need any resolvers or filters:

$phptal->page_content = str_replace('[DATE]', '19-02-1981', 

<div tal:content="structure page_content"/>

regards, Kornel

PHPTAL mailing list

Reply via email to