Skip to content

Instantly share code, notes, and snippets.

@justiny
Last active September 26, 2018 18:25
Show Gist options
  • Save justiny/caf85ca86a322917329c20b7842e7082 to your computer and use it in GitHub Desktop.
Save justiny/caf85ca86a322917329c20b7842e7082 to your computer and use it in GitHub Desktop.
Blog with Pagination in Timber
<?php
/**
* Template Name: Blog
**/
global $paged;
if (!isset($paged) || !$paged){
$paged = 1;
}
$context = Timber::get_context();
$args = array(
'posts_per_page' => 6,
'paged' => $paged
);
$context['posts'] = new Timber\PostQuery($args);
// render the query
Timber::render('components/blog.twig', $context);
<div class="es-col-xs-5 border-left-1">
<div class="content-inner xs-pl-30 xs-pt-40 xs-pb-40">
<h1 class="t-1 xs-mb-20">Blog w/ Pagination</h1>
<p class="text-22 xs-mb-20">Here is an example of grabbing a specified number of posts by using the <span class="code">Timber\PostQuery</span> object called from a custom page template, aptly named Blog.</p>
<section class="es-blog">
<div class="es-row">
{% for post in posts %}
<div class="es-col-xs-6 es-col-sm-3 xs-mb-40">
{% if post.thumbnail %}
<img src="{{ post.thumbnail.src|resize(600, 400) }}" />
{% endif %}
{# grab post title #}
<h2 class="xs-mt-20 xs-mb-20"><a href="{{post.link}}" class="text-black link-underline">{{post.title}}</a></h2>
{# grab content w/ excerpt #}
<p class="text-22 xs-mb-20">{{post.post_content|excerpt(20)}}...</p>
{# grab first category only #}
<p><a href="{{post.category.link}}">{{post.category}}</a></p>
{# grab all categories w/ no link #}
<p>{{ post.terms('category') | join(', ') }}</p>
{# grab all categories w/ link #}
<p>Categories: {{ function('the_category', ', ') }}</p>
{# grab all tags w/ link #}
<p>{{ function('the_tags') }}</p>
</div>
{% endfor %}
</div>
<div class="es-blog-pagination">
{% if posts.pagination.prev %}
<a href="{{posts.pagination.prev.link}}" class="prev {{posts.pagination.prev.link|length ? '' : 'invisible'}}">Prev</a>
{% else %}
<a href="" style="opacity:.2" class="prev disabled {{posts.pagination.prev.link|length ? '' : 'invisible'}}">Prev</a>
{% endif %}
<ul class="es-blog-pagination-nav">
{% for page in posts.pagination.pages %}
<li>
{% if page.link %}
<a href="{{page.link}}" class="{{page.class}}">{{page.title}}</a>
{% else %}
<span class="{{page.class}}">{{page.title}}</span>
{% endif %}
</li>
{% endfor %}
</ul>
{% if posts.pagination.next %}
<a href="{{posts.pagination.next.link}}" class="next {{posts.pagination.next.link|length ? '' : 'invisible'}}">Next</a>
{% else %}
<a href="/" style="opacity:.2" class="next {{posts.pagination.next.link|length ? '' : 'invisible'}}">Next</a>
{% endif %}
</div>
</section>
</div>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment