You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Drupal集成CAS登录场景下,如何通过BigPipe配置避免主题用户名片段缓存历史用户信息

Fixing Stale Username Display with BigPipe in Drupal

It sounds like you're hitting a classic cache context issue—your username snippet is being cached as part of the public page content, so BigPipe isn't swapping in the current user's name when a new user logs in. Here's how to fix this properly:

Root Cause

BigPipe works by splitting the page into cached (public) and uncached (user-specific) segments. Your {{user.displayname}} is being treated as public content right now, so it's stuck in the cache with the previous user's data. We need to tell Drupal this piece of content is tied to the current user context.

The most reliable way is to update your theme's preprocessing function to flag the user variable as user-specific. This tells BigPipe to handle it as personalized content.

  1. Open your theme's .theme file (e.g., mytheme.theme)
  2. Add one of these preprocess functions depending on where your header template is processed:

For page-level preprocessing:

/**
 * Implements hook_preprocess_page().
 */
function mytheme_preprocess_page(&$variables) {
  if (isset($variables['user'])) {
    // Mark this user data as tied to the current user context
    $variables['user']['#cache']['contexts'][] = 'user';
    // Optional: If you want to disable caching entirely for this element
    // $variables['user']['#cache']['max-age'] = 0;
  }
}

For header-specific preprocessing (if your header has its own preprocess hook):

/**
 * Implements hook_preprocess_header().
 */
function mytheme_preprocess_header(&$variables) {
  if (isset($variables['user'])) {
    $variables['user']['#cache']['contexts'][] = 'user';
  }
}
  1. Save the file and clear all Drupal caches (via /admin/config/development/performance or Drush: drush cr)

Solution 2: Use Twig Cache Tags (Alternative)

If you prefer to handle it directly in the Twig template, you can wrap the username snippet in a {% cache %} block with the user context:

In your header.twig.html:

{% cache contexts ['user'] %}
  <span id="user_name">{{ user.displayname }}</span>
{% endcache %}

This tells Twig to cache this segment per user, so each user gets their own version of the username.

Critical Checks

  • Ensure BigPipe is enabled: Go to /admin/config/development/performance and confirm "BigPipe" is checked under "Advanced aggregation".
  • Verify your user variable is the current authenticated user: Double-check that the user object passed to your header template is indeed the logged-in user (not a static or cached object).

After making these changes, test by logging in with different users—your welcome username should now correctly update for each user instead of showing the previous one.

内容的提问来源于stack exchange,提问作者user1689274

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 10:02:43