Call a method in an article?

Hello :slight_smile:
I have a new question for you!

I made this method:

 page::$methods['age'] = function($page) {
    $then = '1991-09-06';
    $then = date('Ymd', strtotime($then));
    $diff = date('Ymd') - $then;
    return substr($diff, 0, -4);
};

Yes a very simple one! Btw. how can I give the method a value?

But know the main question: Can I use this method in a article.txt ? Or home.txt?

(sorry for my bad english)

Greetings,
Sebastian

You can use this method in any php file, i.e. a template, controller, snippet whatever. It is not possible to use php code in a text file, it would not be executed but simply stored as a string.

I don’t really see your use case for storing the code in a text file, anyway?

If you want to pass an argument:

 page::$methods['age'] = function($page, $date) {
    $then = date('Ymd', strtotime($date));
    $diff = date('Ymd') - $then;
    return substr($diff, 0, -4);
};

Then call like this

$page->age($page->date());
// or whatever the field is that you want to transform

But since you probably want to calculate the value from an existing field, I’d suggest using a field method instead of a page method.

Edit: I forgot that this does not work with a field called date, because the date field is a special field that returns an integer instead of a field object. So you would have to call the field that contains the date something else, lets call it birthday in this case:

field::$methods['toAge'] = function($field) {
  // create a DateTime object from the field that is not called `date`
  $d1 = new DateTime($field->value());
  // create a DateTime object from the current date
  $d2 = new DateTime(date('ymd'));
  // get the difference
  $diff = $d2->diff($d1);

  // return the number of years
  return $diff->y;
};

In your template:

echo $page->birthday()->toAge();

Edit: with the field method above, and a field called date, you can also do this:

echo $page->content()->date()->toAge();
1 Like

Thanks thats nice and works fine for me :slight_smile: !