Search code examples
octobercmsoctobercms-plugins

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


My page 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>

Considering I'm getting the data from the component "cities" and that the actual data is retrieved when I call the getCity method in twig how do I dynamically pass a variable to the onEnd() function to inject a custom title based on the content?

Update #1: @Hardik Satasiya I want to set the title from the component but I don't want to call a specific method in onRender() since that assumes that every time I need that component I need to call getCity which is not always the case.

However, your example (method 2) returns

Trying to get property 'name' of non-object

for

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

Because it's probably not passed to the page like my first attempt. I think there's something missing. I want in this order to

  • set the component and method in twig (NOT in the PHP section)
  • set in the component a var that will be available to the page's PHP section
  • set the title from the PHP section of the page based on the comportment output

Probably not possible due to how the page cycle is designed?


Solution

  • There are 2 ways of accessing city.

    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

    In your cities component onRender method

    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;
    }
    
    

    This should solve your issue.

    If any doubt please comment.