是否可以使用绝对路径渲染局部?

Is it possible to render a partial using absolute path?

我正在开发一个 OctoberCMS 插件,它有一个组件,该组件根据提供给该组件的模型中的数据呈现不同的部分。我遇到的问题是,如果它属于组件或主题部分文件夹,我似乎只能呈现部分。我希望能够从其他插件注册新的模型类型,并将它们的视图放在同一个插件文件夹中,例如:

我基本上希望主要组件的 onRender 决定渲染哪个部分,例如:

public function onRender()
{
    // Some code here to determine which partial to render

    return $this->renderPartial($pathToPartial);
}

好的,那好,我们可以使用 2 个引擎 1. default PHP 另一个是 2. twig

对于PHP引擎

First we need to add helper ViewMaker trait in to component

class CompoOne extends ComponentBase
{    
    use \System\Traits\ViewMaker; // <- we need to add partial/view related method makeView

Now we will add two methods render method and custom Render method

因为我不想覆盖默认行为,所以我将添加 extensioncustom 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';

}

This will let component render its default partial default.htm. Now it's code

<h1>Component Parital</h1>
<div class="dynamic-partial">
    {{__SELF__.customRender()|raw }}
<div>

And our custom partial $/hardiksatasiya/demotest/main , it will be like my_project_root_path/plugins + /hardiksatasiya/demotest/main here main will be main.htm automatically so main.htm code

<div class="my-partial">
    Its ok to have partial <?= $model ?>.
</div>

此组件的最终 out-put 将是

<h1>Component Parital</h1>
<div class="dynamic-partial">
    <div class="my-partial">
        Its ok to have partial your model.
    </div>
</div>

Execution Flow

第一个 onRender 将在这里调用,我们设置 vars 将包含 partial path [你可以从组件配置或其他]

它将调用 default.htm 这将调用我们自定义的 customRender 方法

现在我们 finally 调用我们的 dynamic partial,在它里面所有我们在 $this->vars[] 里面定义的变量都将自动可用。 [在演示中我添加了 $this->vars[[=​​80=]] 这样的 ]

对于 Twig 引擎

只需遵循 PHP 引擎步骤和此说明

We don't need to add helper ViewMaker trait in to component (so skip that step)

We change our custom Render method to use twig engine

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

Our custom partial file code will be

<div class="my-partial">
    Its ok to have partial {{ model }}
</div>

out-put 同上

We can use twig tags here and all the variables which will be assigned to $this->vars will be available inside the partial

如有疑问请评论