如何从 octoberCMS 中的组件数据设置动态页面标题?

How to set dynamic page title from a component data in octoberCMS?

我的页面city.htm

title = "city"
url = "/data/:countryslug/:cityslug"
layout = "default"
is_hidden = 0

[cities]
==
function onEnd()
{
    $this->page->title = '?';
}
==
{% set city = cities.getCity %}

<div class="content">
</div>

考虑到我正在从组件“cities”获取数据,并且当我在 twig 中调用 getCity 方法时检索到实际数据,我如何动态地将变量传递给 onEnd() 函数以注入自定义标题基于内容?

更新#1: @Hardik萨塔西亚 我想从组件设置标题,但我不想在 onRender() 中调用特定方法,因为这假设每次我需要该组件时我都需要调用 getCity,但情况并非总是如此。

但是,你的例子(方法二)returns

Trying to get property 'name' of non-object

function onEnd()
{
    $this->page->title = $this['city']->name; //error
}

因为它可能没有像我第一次尝试那样传递到页面。 我认为缺少一些东西。 我要按这个顺序

由于页面周期的设计方式,可能无法实现?

有两种访问城市的方式。

  1. Very easy one if you don't want other features
function onEnd()
{
    $city = $this->components['cities'].getCity();
    $this->page->title = $city->name;
}

2. If you need more control and reuse variable at other places

在您的 cities 组件 onRender 方法中

public function onRender()
{
    // to just share variable to page
    $this->page['city'] = $this->getCity();

    // to share variable top page and component partial
    $this->city = $this->page['city'] = $this->getCity();
}

Now, from page code section

function onEnd()
{
    // $this->page['city'] <- we do this in component 
    // So, here we can access it directly   
    $this->page->title = $this['city']->name;
}

这应该可以解决您的问题。

如有疑问请评论。