【问题标题】:Passing Viewbag variable to Component from Theme settings将 Viewbag 变量从主题设置传递给组件
【发布时间】:2020-05-28 13:01:33
【问题描述】:

在 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 但没有成功。关于如何做到这一点的任何想法?

【问题讨论】:

    标签: octobercms octobercms-plugins octobercms-backend


    【解决方案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
    }
    

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

    【讨论】:

    • 我设法使用 onInit 方法使用 $perPage = $this->theme->product_count; $this->page->components['featuredProducts']->setProperty('perPage', $perPage);你的方法有什么不同?
    • 我的方法不太通用,标准意味着你可以看到它更简单易读。另外,如果您需要更改主题变量名称等,例如product_count ,您可以从后端进行,您无需打开组件文件。我的方法也更具可读性..意味着下次你可以看到并了解正在发生的事情..在你的方法中很难理解这个perPage来自哪里......以太方式取决于你喜欢什么: )
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-05
    • 1970-01-01
    • 2019-09-15
    • 2020-07-23
    • 2021-11-06
    相关资源
    最近更新 更多