将变量传递给 October Cms 博客帖子组件

Passing variable to Octobercms blogPosts component

在 Octobercms blogPosts 组件上,我想传递一个变量。我想使用以下方式更改 postsPerPage 值:

{variable name="blog_postnumber" label="postnumber" tab="postnumber" type="number"}{/variable}

静态布局。所以我希望能够在静态页面上使用此字段更改 postsPerPage 组件值。

我将部分内容与 blogPosts 组件结合使用。在组件 postsPerPage 字段上,我插入了变量。

postsPerPage = "{{ blog_postnumber }}"

然后我尝试在我的静态页面上的字段中插入一个数字,但没有用。关于如何在组件上传递变量的任何想法?

你将 variable/property 传递给组件 will be used or not 真的很棘手。如果 属性 在组件的 onRender 方法中获取,它将被使用。如果它在 onRun 上使用,那么它将不会被使用。 (其 OctoberCMS 设计)

for blogPosts component its in onRun so when you pass property like this {% component 'blogPosts' postsPerPage="2" %} it will not be used, But To handle this we need other work-around


(1) for the component blogPosts you included in partial you need to use property from param. check screen shot.

(2) In you Static layout's Code section you need to add this code

public function onStart() {
    $statiPage = $this->page->apiBag['staticPage'];
    // default posts per page
    $defaultBlogPost = 5;
    if(isset($statiPage->viewBag['blog_postnumber'])) {
        // fetching value from the page field
        $defaultBlogPost = intVal($statiPage->viewBag['blog_postnumber']);
        $router = $this->getRouter();
        // combine with existing params
        $router->setParameters(['myBlogPerPage' => $defaultBlogPost] + $router->getParameters());
    }               
}

并且在标记部分字段中

{variable name="blog_postnumber" label="postnumber" tab="postnumber" type="number"}{/variable}

(3) Now you can start using it set variable value we set it by default 5 in code section, to override it specify value in page's postnumber field section

它将开始工作。

如有疑问请评论。