Search code examples
octobercmsoctobercms-pluginsoctobercms-backend

Passing Viewbag variable to Component from Theme settings


On Octobercms theme settings i use a yaml file:

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

On index.htm page i use a partial featuredProducts of component with alias featuredProducts

On component featuredProducts viewBag i use this variable:

perPage = "{{ product_count }}"

I try to pass variable product_count from theme settings yaml file to components viewBag but without success. Any idea on how can do it?


Solution

  • You need to use component's property functionality and it's onRender() method.

    Page's markup section

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

    Component's onRender() method: make sure to use onRender() method as props will be available there.

    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
    }
    

    If any doubts please comment.