4

My goal is to simply output something only on the index page of my wordpress using Twig code. I have set a static page called Home.

I have tried this in my base.twig:

{% if is_front_page %}
 Homepage content
{% endif %}

But this doesn't do anything and I just find can't easily find it for some reason.

Any help is appreciated! Thanks in advance

Noob17
  • 709
  • 2
  • 7
  • 21

3 Answers3

19

Timber comes with the fn (also has alias of function) that let's you execute external PHP functions. So something like this would work:

{% if fn('is_front_page') %}
  Homepage content
{% endif %}
Anonymous
  • 11,740
  • 3
  • 40
  • 50
  • Nice I had already found a solution but this another way to do it! Thanks for letting me know about this function! – Noob17 Aug 02 '15 at 22:58
11

I like to keep special functions outside of my twig templates. In Timber you can define your own context where you can set your own variables.

Create a file called front-page.php and add:

<?php

$context = Timber::get_context();

// Set a home page variable
$context['is_front_page'] = 'true';

Timber::render(array('home.twig'), $context);

then you can use is_front_page as a variable just like you wanted:

{% if is_front_page %}
 Homepage content
{% endif %}
Jason Rambeck
  • 111
  • 1
  • 3
2

You can create a global content by extending the timber_context fitler.

Add the below into you functions.php file and it will add to all templates using calling Timber::get_context();.

add_filter('timber_context', 'add_to_context');
function add_to_context($context){
    /* Add to Timber's global context */
    $context['is_front_page'] = is_front_page();
    return $context;
}
WPhil
  • 1,056
  • 1
  • 7
  • 12