Useful Timber, Twig Functions and Filters
Timber has a few tricks up its sleeve that can make your life much easier. This page is meant as a collection of useful manipulations that you can build on.
TimberImage()
{# Perhaps one of the easiest ways to manipulate an image: #}
<img src="{{ TimberImage(post.thumbnail).src('medium') }}">
{# Display the featured image (fi) of size medium if available #}
<img src="{{ TimberImage(post.thumbnail).src('medium')|resize(300,200, 'center') }}">
{#
Display the image of size medium, resize to 300x200 and from center if ratio is off.
Alternatives on third parameter are:
'default', 'center', 'top', 'bottom', 'left', 'right', 'top-center', 'bottom-center'
#}
<img src="{{ TimberImage(post.thumbnail).src('medium')|letterbox( 300,300, '#ffffff') }}">
{#
Display the fi image of size medium, resize it to fit proportionally to a box
of dimensions 300x300pixels, use #ffffff as background color for remaining pixels.
#}
<img src="{{ TimberImage(post.thumbnail).src('medium')|resize(300) }}">
{# Display the fi image of size medium, resize proportionally and use max width 300 pixels. #}
<img src="{{ TimberImage(post.thumbnail).src('medium')|resize(0,300) }}">
Post()
Working with relationships fields or getting data from another post ID can be frustrating, but not with Timber:
{% set postids = [ 22,45,67 ] %}
{% for item in postids %}
{% set item = Post( item ) %}
<img src="{{ item.thumbnail.src('thumbnail') }}" alt="{{ item.thumbnail.alt }}">
<a href="{{ item.link }}"><h4>{{ item.title }}</h4></a>
{% endfor %}
Is all it takes to get the thumbnail, link and title on an array of postids.
PostQuery()
The Timber Post Module allows us to set a basic custom query and returns Timber Post Objects. There is a slight difference between regular WP Post Objects, and these Timber Post Ojects, and that’s what makes Timber so great. You have direct access to Terms, Thumbnail, pagination and much more.
But the PostQuery() method within a Timber Template allows you to make new or additional queries and also have all the great features mentioned here.
{%
set args = {
post_type: 'post',
posts_per_page: 5,
}
%}
{% set posts = PostQuery( args ) %}
{% for item in posts %}
<h4>{{ item.title }}</h4>
{% endfor %}
set
Used to create a (temporary) variable. You can use it to store a portion of an array for a more a readable template, or to store extra data.
{#
Use TimberImage to get an attachment ID from the WordPress media library.
Store it as a variable image so we can reuse it multiple times to get all data
#}
{% set image = TimberImage(45) %}
<img src="{{ image.src( 'full' ) }}" alt="{{ image.alt }}" width="{{ image.width }}" height="{{ image.height }}">
ne go.