通过主题设置将Viewbag变量传递给组件

时间:2020-05-28 13:01:33

标签: octobercms octobercms-plugins octobercms-backend

在Octobercms主题设置上,我使用了Yaml文件:

product_count:
    label: Number
    type: number
    span: left
    tab: Index
    default: 3

在index.htm页面上,我使用部分featuredProducts的组件,别名为featuredProducts

在组件featuredProducts的viewBag上,我使用以下变量:

perPage = "{{ product_count }}"

我尝试将变量product_count从主题设置yaml文件传递到组件viewBag,但没有成功。关于如何做到这一点的任何想法?

1 个答案:

答案 0 :(得分:1)

您需要使用组件的property功能及其onRender()方法。

页面的标记部分

{% component 'featuredProducts' perPage=this.theme.product_count %}

组件的onRender()方法:请确保使用onRender()方法,因为道具在那里可用。

public function onRender() {
    // with default value of 3, if theme value is not already set
    $perPage = $this->property('perPage', 3); 

    // now use $perPage to fetch records
    $this->page['items'] = SomeModel::limit($perPage)->get();

    // items will be available in markup for use
}

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