如何从 OctoberCMS 中的代码访问标记树枝变量

How to access markup twig variable from code in OctoberCMS

我正在尝试从 octoberCMS 代码模块中的标记 (Twig) 访问变量。该变量由插件构建器循环打印。

我在标记中有这个变量:

{% set frontId = record.id %}
{{frontId}}

我想在代码模块中访问 {{frontId}} 变量。

function onStart()
{
    $this["slots"] =  Db::table('oblikovanje_izobrazevanja_vnos')->where('id', $frontId)->value('free_slots');
    echo $frontId;
}

嗯,很遗憾,您不能将变量从 Markup 传递到 Code 部分。因为 Code 部分在 Markup 之前执行,所以你不能那样做。

您似乎正在使用 Builder 的 Record details 组件,因此您必须从 url

传递 :id

Solution 1 [ use param ]

function onStart() { // you can use onEnd as well
    $frontId = $this->param('id'); // this will get :id param from url

    // now slots variable are available in `Markup section`    
    $this["slots"] =  Db::table('oblikovanje_izobrazevanja_vnos')->where('id', $frontId)->value('free_slots');

}

Solution 2 [ you can use global component array with its alias name, make sure to use onEnd life-cycle hook ]

function onEnd () { // you must use onEnd as at this moment all components are initialized properly 

    // we can access component from $this->components with alias name and get its details
    $frontId = $this->components['builderDetails']->record->id;

    // now slots variable are available in `Markup section`    
    $this["slots"] =  Db::table('oblikovanje_izobrazevanja_vnos')->where('id', $frontId)->value('free_slots');

}

Reference Screenshot

如有疑问请评论。