bcosca / fatfree

A powerful yet easy-to-use PHP micro-framework designed to help you build dynamic and robust Web applications - fast!
2.66k stars 446 forks source link

Modify output of DOM tree before display. #1243

Closed maietta closed 2 years ago

maietta commented 2 years ago

I'd like to extend the Template to work on the html tag, but it seems that processing ends when extending the template function. I'd like to hook into the framework AFTER rendering but before display. I'm pretty much lost. My only other option seems to be to use object buffering a feature of PHP that I don't like because I use it for some part of a website I am working on and it's not a clean hack for many reasons.

A simple example is to extend the template:

\Template::instance()->extend('title','DOM::ammendTitle');

Then have the following class:

class DOM {

    static public function ammendTitle($args) {
        $attr = $args['@attrib'];
        return '<title>'.$args[0].' ~ ACME Demo, Inc.</title>';
    }

}

What I end up with is interesting:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>{{ @page_title }} ~ ACME Demo, Inc.</title>

        <link rel="apple-touch-icon" sizes="180x180" href="/gfx/icons/apple-touch-icon.png">
        <link rel="icon" type="image/png" sizes="32x32" href="/gfx/icons/favicon-32x32.png">
        <link rel="icon" type="image/png" sizes="16x16" href="/gfx/icons/favicon-16x16.png">
        <link rel="manifest" href="/gfx/icons/site.webmanifest">
        <link rel="mask-icon" href="/gfx/icons/safari-pinned-tab.svg" color="#5bbad5">
        <link rel="shortcut icon" href="/gfx/icons/favicon.ico">
        ...

I did not expect to see that my template variables are no longer rendered after "extending" the Template method. The {{ @page_title }} no longer gets rendered.

While it seems like I might be on the right path to do what I need, I am running into the fact that when I extend the template with this method, I don't see the rendered output. I'd like to access the rendered template before display. Looking over the source code, I haven't found a way.

Any advise is greatly appreciated. Thanks!

ikkez commented 2 years ago

You have to compile any variable tokens yourself in the expend method. Actually the script does not know what you want to do with $args[0] so it's up to you to use it as string or a dynamic variable. There should be some details about that in the docs. If you want to access the template after rendering neverthless, have a look at the afterrender hook for the template

maietta commented 2 years ago

First of all, THANK YOU, @ikkez.

I've been using Fat Free Framework since, oh, well 2016 I think and have poured over documentation over and over. For whatever the reason, I have never seen the afterrender hook.

I'll give this a go.