4
votes

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

3

3 Answers

16
votes

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 %}
11
votes

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 %}
1
votes

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;
}