-3

I created two custom blocks. I want to display its two blocks only when the home page view is empty.

I want the custom block with id 11 to be displayed for anonymous users.

I want the custom block with id 12 to be displayed for authenticated users.

So I copied the views-view--frontpage.html.twig template into my sub-theme.

What should I add in the code, to obtain this result ? Thanks

  {% if rows %}
    <div class="view-content">
      {{ rows }}
    </div>
  {% elseif empty %}
    {{ empty }}
  {% endif %}
1
  • Welcome to Drupal Answers! This question doesn't meet our guidelines. You should show that you did some research and include in the question what you have tried so far. Please have a look at the Help Center and make sure to read How do I ask a good question?.
    – berliner
    Commented Oct 8, 2022 at 10:35

1 Answer 1

0

The title to this question asks a pretty simple question, but the need to show content based on user login complicates things a bit.

There are several ways to accomplish your task, including creating a custom Views Area Handler Plugin where you render the blocks you want programmatically with the if statement checking for a logged in user. See How to create a simple views area plugin. You would then set that plugin in the "No results behavior" section of your view.

Another way would be to use views hooks found in views.api.php to accomplish this. Keep in mind the views hook run order. In this way, you likely add both blocks to the "No results behavior" using the "Global: Rendered entity - Custom block" plugin. In likely any of hook_views_post_build, hook_views_pre_execute, views_post_execute, or views_pre_render would do the same check to see if a user is logged in but remove one of the blocks from the empty portion of the view's display options based on the results.

If you want to do this in the theme layer, (which I'm making an assumption you do since you posted a twig file), you will need to use a preprocessor for your view, setting a variable to check to see if the user is logged in with a solution simular to this one. Then I would suggest installing and using Twig Tweak and using twig to render the blocks you want as defined in their documentation.

Your preprocessor would end up something like:

function mymodule_preprocess_views_view(&$variables) {
  if ($variables['view']->id() == 'frontpage') {
    $variables['logged_in'] = \Drupal::currentUser()->isAuthenticated();
  }
}

Your twig would end up looking something like

  {% if rows %}
    <div class="view-content">
      {{ rows }}
    </div>
  {% elseif empty %}
    {% if logged_in %}
      {{ drupal_entity('block_content', '12' ) }}
    {% else %}
      {{ drupal_entity('block_content', '11' ) }}
    {% endif %}
  {% endif %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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