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

时间:2018-02-15 15:10:54

标签: octobercms

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

  • 模型
    • 为MyModel
      • view.htm
    • MyModel.php

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

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

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

1 个答案:

答案 0 :(得分:0)

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

对于PHP引擎

  

首先,我们需要将helper ViewMaker trait添加到组件

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

现在我们将添加两个方法render methodcustom 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 [您可以将其从组件配置或其他内容中添加]

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

现在我们finally调用我们的dynamic partial,其中包含我们在$this->vars[]内自动定义的所有变量。 [在演示中我添加了$ this-&gt; vars [&#39; model&#39;]像这样]

For Twig Engine

只需按照说明使用PHP引擎步骤

  

我们不需要在组件中添加帮助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

如果您有任何疑问,请发表评论

相关问题