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

如何限制非管理员查看PHP错误?修改Twig模板遇错求助

Fix: Restrict Error Messages to Admins Only in Drupal

Let's tackle this issue step by step. The reason setting "Error message to display" to none didn't work is that this global setting controls which error types are logged/displayed system-wide—it doesn't restrict visibility exclusively to admins. To achieve that, we need to modify the template with proper access checks, and I'll show you the correct way to do it (since your initial attempt threw an error likely due to missing user context).

Correct Template Modification for status-messages.html.twig

Replace your existing code with this:

{% block messages %}
  {% set current_user = current_user() %}
  {% if message_list is not empty and (current_user.isAdmin() or current_user.hasPermission('access administration pages')) %}
    {{ attach_library('bartik/messages') }}
    <div class="messages__wrapper layout-container">
      {{ parent() }}
    </div>
  {% endif %}
{% endblock messages %}

What This Does:

  1. Get the Current User: We use Drupal's current_user() service to fetch the active user object—this avoids the "undefined variable" error you saw earlier when trying to use is_admin directly.
  2. Admin Access Check: We check two conditions to show messages:
    • There are messages to display (message_list is not empty)
    • The user is either an admin (current_user.isAdmin()) or has the access administration pages permission (adjust this permission to match your needs if required).
  3. Preserve Existing Functionality: We keep the library attachment and wrapper markup so the messages still look like they did in Bartik.

Post-Modification Steps:

  • Clear Drupal Cache: Template changes won't take effect until you clear the cache. You can do this via the admin UI (Configuration → Performance → Clear all caches) or run the Drush command: drush cr
  • Test with Different Users: Log in as a regular user to confirm errors are hidden, then as an admin to verify they're still visible.

Why Your Initial Attempt Failed:

Using is_admin directly in the template throws an error because that variable isn't available by default in the status-messages.html.twig context. You must explicitly fetch the user object via the current_user() service to perform access checks.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 06:46:46