7.3. 在 Drupal 中禁用缓存,并在模板中输出调试信息。
在开始 Drupal 8 开发之前,您必须先禁用缓存。与 Drupal 7 不同,在 Drupal 8 中,不仅实体(entity)、视图(views)、字段(fields)会被缓存,连编译后的 Twig 模板 和 Render 模板 也会被缓存。要禁用所有这些缓存,请按照以下步骤操作:
1. 复制文件:
将 /sites/example.settings.local.php
文件复制为 /sites/default/settings.local.php
。
此文件中已包含用于禁用缓存的必要配置。
2. 在 settings.php
文件中取消注释以下代码:
这样可以启用我们刚创建的 settings.local.php
文件。
if (file_exists(__DIR__ . '/settings.local.php')) {
include __DIR__ . '/settings.local.php';
}
这样就会启用 settings.local.php
。
3. 确保在 settings.local.php
中以下行已取消注释:
$settings['container_yamls'][] = DRUPAL_ROOT . '/sites/development.services.yml';
development.services.yml
文件已默认存在,只需启用即可。
4. 检查是否禁用了 CSS 与 JavaScript 聚合:
在 settings.local.php
中确保如下配置:
$config['system.performance']['css']['preprocess'] = FALSE;
$config['system.performance']['js']['preprocess'] = FALSE;
5. 禁用渲染缓存与动态页面缓存模块的缓存:
$settings['cache']['bins']['render'] = 'cache.backend.null';
$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';
在 settings.local.php
中找到这些行并取消注释。
6. 禁止 Drupal 扫描模块测试:
将以下配置设为 FALSE
:
$settings['extension_discovery_scan_tests'] = FALSE;
7. 修改 /sites/development.services.yml
文件:
在文件中添加以下内容:
parameters:
twig.config:
debug: true
auto_reload: true
cache: false
最终的 development.services.yml
文件应如下所示:
# Local development services.
#
# To activate this feature, follow the instructions at the top of the
# 'example.settings.local.php' file, which sits next to this file.
services:
cache.backend.null:
class: Drupal\Core\Cache\NullBackendFactory
parameters:
http.response.debug_cacheability_headers: true
twig.config:
debug: true
auto_reload: true
cache: false
注意:在 .yml
文件中,必须严格保持换行与缩进规则,只能使用两个空格缩进,不能使用 Tab。
debug: true
该参数负责在页面上输出每个可被覆盖的模板名称。这有助于分析和学习 Drupal 8 模板结构。虽然在某些情况下可能会影响页面布局或导致少数模块报错,但总体来说是一个非常实用的调试功能。
8. 最后一步:清理缓存。
可以使用 Drush 命令:
drush cr
或者通过浏览器运行以下地址:
http://yoursite/core/rebuild.php