Hey guys, I've been looking for a way to do this for a few days now and I can't find any solution. I'm currently using the Timber Starter Theme.
All I'm trying to do is add three recent posts to the static front page using Timber. I've tried rendering the home.twig file into the front-page.twig file, but that just causes a huge mess. I've tried using blocks to bring the posts over to the front-page, but nothing.
I've been pouring over the documentation, and either what I'm looking for isn't there or I've looked at it too many times and am just missing it. I guess a secondary question would be, is this even possible using Timber?
You want to first make sure you are working with the right PHP template file in your theme. That could be, in order of precedence:
page-{id}.php, page-{slug}.php, page.php, index.php
If you did not change this part of the starter theme, it should be _page.php_.
Within that file, you could then add some code like this:
$data = Timber::get_context();
$data['page'] = new TimberPost();
$templates = array('page.twig');
if (is_front_page()){
// get latest three posts
$args = array(
'posts_per_page' => 3
);
$data['posts'] = Timber::get_posts($args);
// add your twig view to the front of the templates array
array_unshift($templates, 'my-static-home.twig');
}
Timber::render( $templates, $data );
Then in _my-static-home.twig_:
<h1>{{ page.title }}</h1>
{{ page.content }}
<h2>Recent posts</h2>
<ul>
<% for post in posts %>
<li><a href="{{ post.link }}">{{ post.title }}</a></li>
<% end %>
</ul>
Worked like a charm! Thank you!
Hey @jnweaver ,
Maybe you could help me with a similar problem too.
I've created a separate timber file for my front page called - front-page.php - that looks like this
$context = Timber::get_context();
$post = new TimberPost();
$context['post'] = $post;
Timber::render( 'front-page.twig', $context );
I've tried to use your example above but it's not quite working. It's rendering twice and I don't really know how to fix it.
Any help would really be appreciated!
Most helpful comment
You want to first make sure you are working with the right PHP template file in your theme. That could be, in order of precedence:
If you did not change this part of the starter theme, it should be _page.php_.
Within that file, you could then add some code like this:
Then in _my-static-home.twig_: