Is the is_front variable not available in a Paragraphs template override?

I'm trying to do the following:

    <div{{ attributes.addClass(classes) }}>
      <div class="row">
        <div class="col-sm-7">
          {% if is_front and content.field_section_title %}
            <h2>{{ content.field_section_title }}</h2>
          {% elseif content.field_section_title %}
            <h4>{{ content.field_section_title }}</h4>
          {% endif %}

          {{ content.field_text }}
        <div class="col-sm-5">
          {{ content.field_section_image }}

However, when I set a node that uses this paragraph type as the homepage, it doesn't take the is_front condition and just uses the h4 tag instead of the h2 which is what I would like for it to do.

Is there a way for my paragraphs templates to use the is_front condition? Or is there a different way to go about this?


You should be able to add this with a preprocess function in mytheme.theme of your theme.

 * Implements hook_preprocess_paragraph().
 * @param $variables
function mytheme_preprocess_paragraph(&$variables) {
  $variables['is_front'] = Drupal::service('path.matcher')->isFrontPage();

  // Ensure the cache varies correctly.
  // Drupal 8.2.x or lower
  $variables['#cache']['contexts'][] = 'url.path';

  // Ensure the cache varies correctly.
  // Drupal 8.3.x+
  $variables['#cache']['contexts'][] = 'url.path.is_front'; 

This should add is_front as a variable to any paragraph twig template. Clear cache after adding this code.

Per 4k4's comment, if this is Drupal 8.3 you will also need to add a cache context.

  • Excellent. This did the trick. Thanks again Kevin. – ACanadianCoder Jan 17 '17 at 15:37
  • 2
    You also need a cache context url.path. In Drupal 8.3 there will be a new one for this: url.path.is_front - drupal.org/node/2830442 – 4k4 Jan 17 '17 at 16:38
  • @Kevin, I've seen the edited answer about Drupal 8.3, you need the cache context for all D8 versions. Prior to 8.3 you don't have the front page specific one, so you can only use 'url.path'. – 4k4 Jan 17 '17 at 19:07
  • Okay, I updated my answer. – Kevin Jan 17 '17 at 19:12
  • Great, that's a very nice answer! – 4k4 Jan 17 '17 at 19:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.