好吧,我们可以使用 2 个引擎 1.default PHP 另一个是 2.twig
对于 PHP 引擎
首先我们需要在组件中添加助手ViewMaker trait
class CompoOne extends ComponentBase
{
use \System\Traits\ViewMaker; // <- we need to add partial/view related method makeView
现在我们将添加两个方法render method和custom Render method
由于我不想覆盖默认行为,我将添加 extension 和 custom render。
public function customRender() {
// this will be our logic
$partialPath = $this->vars['parialPath'] ?? 'default';
return $this->makeView($partialPath);
}
public function onRender()
{
// this will decide which partial we need to render
$this->vars['parialPath'] = '$/hardiksatasiya/demotest/main';
// $ <- start from plugin dir
// $this->vars['parialPath'] = '~/main';
// ~ <- start from root dir
// data you want to pass to your partial
$this->vars['model'] = 'your model';
}
这将使组件呈现其默认部分 default.htm。现在是代码
<h1>Component Parital</h1>
<div class="dynamic-partial">
{{__SELF__.customRender()|raw }}
<div>
而我们自定义的部分 $/hardiksatasiya/demotest/main ,它会像 my_project_root_path/plugins + /hardiksatasiya/demotest/main 这里 main 将是 main.htm automatically 所以 main.htm 代码
<div class="my-partial">
Its ok to have partial <?= $model ?>.
</div>
此组件的最终输出将是
<h1>Component Parital</h1>
<div class="dynamic-partial">
<div class="my-partial">
Its ok to have partial your model.
</div>
</div>
执行流程
第一个 onRender 将在这里被调用,我们设置 vars 将包含 partial path [你可以把它从组件配置或从 else ]
它将调用default.htm 这将调用我们自定义的customRender 方法
现在我们finally 调用我们的dynamic partial,在其中所有变量都将可用,我们在$this->vars[] 中自动定义。 [在演示中我添加了 $this->vars['model'] 这样的]
对于 Twig 引擎
只需按照此说明执行 PHP 引擎步骤
我们不需要将 helper ViewMaker trait 添加到组件中(所以跳过这一步)
我们将 custom Render method 更改为使用 twig 引擎
public function customRender() {
// twig engine
$partialPath = $partialPath = $this->vars['parialPath'] ?? 'default';
$partialPath = $partialPath . '.htm';
if (\File::isPathSymbol($partialPath)) {
$partialPath = \File::symbolizePath($partialPath);
}
$template = $this->controller->getTwig()->loadTemplate($partialPath);
$partialContent = $template->render($this->vars);
return $partialContent;
}
我们的自定义部分文件代码将是
<div class="my-partial">
Its ok to have partial {{ model }}
</div>
输出和上面一样
我们可以在这里使用twig标签,而all the variables将被分配给$this->vars将是available inside the partial
如有疑问请留言