在 HTMX 中使用 bcosca/fat-free 框架:有没有办法渲染模板片段?

问题描述 投票:0回答:1

我知道使用 INCLUDE 将模板分解为可以多种方式重用的片段,但这会导致许多单独的文件变得难以一致命名和管理。我正在寻找一种方法来指定要呈现的现有模板的子集。这可以是任何包含的块,大概由包含标签上的 id 属性标识。调用渲染语句可能如下所示:

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

其中“#user-form”标识较大模板中的嵌入表单。此功能将与 HTMX 在标签级别处理元素的能力很好地配合。

templates fragment htmx
1个回答
0
投票

回答我自己的问题:我已经使用 HTML 解析器包(paquettg/php-html-parser)和一个返回模板部分的简单函数创建了所需的功能。

在默认控制器中我有:

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>";
    }

此解决方案成功地将任何模板子集化为由 id 标识的块。

© www.soinside.com 2019 - 2024. All rights reserved.