Quick Example: Extending TimberPost

A simple and quick example how to extend the TimberPost class. For what you ask? Well, you have to read the post then.

July 12, 2017

In our agency we use the Twig PHP Template engine to develop our themes. If you didn’t use it yet, I suggest give it a try. Nevertheless, this post will show how to extend the TimberPost class for using your own which has some benefits.

 

Let’s get right into it. First things first, create your own class extending the TimberPost class:

class Falcon extends TimberPost {
    public $_phone_parsed;
    public $_email_antispam;

    public function phone_parsed() {
        if ( !isset( $this->_phone_parsed ) )
            $this->_phone_parsed = parse_phone_for_link( $this->get_field( 'phone' ) );
        
        return $this->_phone_parsed;
    }

    public function email_antispam() {
        if ( !isset( $this->_email_antispam ) )
            $this->_email_antispam = antispambot( $this->get_field( 'email' ) );
        
        return $this->_email_antispam;
    }
}

What is it about: First extending the TimberPost class – obviously. Then, the public functions you wanna have in your custom post class, which then can be called in the twig file – will see in a second. As a bonus, the object members for storing the information in the object itself for improving internal caching, so the execution time can be speeded up.

Now use your custom post class, for example in the page.php:

$context[ 'falcon' ] = new Falcon();
or
$context[ 'falcons' ] = Timber::get_posts( $args, 'Falcon' );

 

Now you can use it in your twig file:

<div class="falcon">
    <h1>{{ falcon.title }}</h1>
    <p>E-Mail: <a href="mailto:{{ falcon.email_antispam }}">{{ falcon.email_antispam }}</a></p>
    <p>Phone: <a href="tel:{{ falcon.phone_parsed }}">{{ falcon.phone }}</a></p>
</div>

 

That’s it. I know, that this example is a very straight forward one, but I guess you can think what you can do with it. With this approach, you have a well suited place where more complex properties can be added without overflowing other parts of your coding structure – helps you to stay DRY ( see what I did there –> overflowing –> DRY –> hä? hä?! 😉 ).

 

Some helpful links:

 

The post image ( the hamster ) is from this guy: Photo by Ricky Kharawala