Using bcosca/fat-free framework with HTMX: Is there a way to render a template fragment?

17 views Asked by At

I am aware of using INCLUDE to break a template into fragments that can be reused in multiple ways but this leads to many separate files that can become difficult to name and manage consistently. I am looking for a way to specify a subset of an existing template to be rendered. This could be any contained block, presumably identified by an id attribute on the containing tag. The invoking render statement might look like:

echo Template::instance()->renderFragment('main.html', '#user-form');

where '#user-form' identifies an embedded form in the larger template. This capability would mesh very well with HTMX ability to process elements at the tag level.

1

There are 1 answers

0
meljturner On

Answering my own question: I have created the required functionality using an HTML Parser package (paquettg/php-html-parser) and a simple function that returns a template partial.

Within the default Controller I have:

use PHPHtmlParser\Dom;
...
...
    protected function partial($template, $id) {
        // renders a template then returns a single block identified
        // by $id as a partial. All F3 substitutions are made prior
        // filtering the selected block so all required hive variables
        // must be set.
        
        $dom = new Dom;
        $html = Template::instance()->render($template);
        $dom->loadStr($html);
        $blk = $dom->find("#$id")[0];
        return $blk ? $blk->outerHtml : "<h2>$id not found.</h2>";
    }

This solution successfully subsets any template to a block identified by an id.