Jump to content

Recommended Posts

Posted

Hello,

The Hook API documentation is great in explaining how hooks work.

I wanted to know if it's possible to add a method or property to a Page, but pages only of a specific template type.

The reasoning behind this would be certain methods or properties would only apply to specific template types.

Possible?

Thank you.

Posted

Thanks for that resource Adrian.

However, I don't think that approach will work for what I have in mind.

For example, let's say I'm on a page that is of the template "car" that lists all the details of the car.  Naturally, this gets stored in $page.

Then let's say while still on that page I want to output the content of a separate page of a totally different template... let's call it "computer".

$mycomputer = $pages->get("/computers/macbook-pro/");

At this point, both $page (which has a template of "car") and $mycomputer (which has a template of "computer") are of the Page class, but of different templates.  Naturally, some methods would apply to "car" and some would apply to "computer".

So, for example, would it be possible to add a property called "hello" to just a Page of template "computer", even without being on the "computer" template?

Posted

I think I see your point now - maybe if you can explain exactly what you need the hook to do it might be easier to figure out the best approach.

Posted

The answer is relatively simple and there would be different ways but best would be to:

In a autoload module (HelloWorld.module) add the hook to ready() where the page being rendered is already set in $this->page

So this would only add property to basic-page templates:

public function ready(){
    if($this->page->template == "basic-page"){
        $this->page->addHookProperty('hello', $this, 'helloHook');
    }
}

public function helloHook(HookEvent $event){
    $event->return = "Hello World";
} 

After all I'm not sure this would make a lot of difference to just add it pages globally. But I could see this being useful for certain situations.

  • Like 4
Posted

You can also just check the page type within the hook function. By simply issuing a 'return' if it doesn't match the template you want, that duplicates the behavior of accessing an unknown property (resulting in a null value being returned to the caller). 

wire()->addHookProperty('Page::hello', function($event)) {
  if($event->object->template != 'basic-page') return; 
  $event->return = 'hi';
}); 
  • Like 1
  • 3 years later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...