海洋射线媒体 / 随机英雄背景
传递字符串数组并返回清除缓存的单个字符串
1.0.2
2020-08-10 08:44 UTC
Requires
- php: >=7.2
- drupal/core: ^8.8.0 || ^9.0
This package is auto-updated.
Last update: 2024-09-25 01:27:01 UTC
README
为了解决匿名用户的缓存问题,我们一直在处理3个不同的文件
pubmlst/web/themes/custom/pubmlst/pubmlst.theme pubmlst/web/modules/custom/random_hero_bg/
node--front.html.twig
为了在英雄部分应用不同的随机背景颜色,并且在不总是缓存结果的情况下随机化颜色,我们使用了随机化颜色的模块
{% set hero_rand_bg = ['bg-blue','bg-purple','bg-teal','bg-navy'] | randomBackground(hero_rand_test) %}
random_hero_bg 自定义模块
在 RandomHeroBG.php 中,我们有两个函数,一个函数用于首先清除匿名用户的缓存
{
\Drupal::service('page_cache_kill_switch')->trigger();
\Drupal::service('cache.render')->invalidateAll();
// clear caches for anonymous
Cache::invalidateTags(['HIT']);
}
然后另一个函数用于在再次随机化值之前删除随机背景颜色。
public function randomBackground(array $input, $number)
{
$this->clearCache();
$key = array_rand($input);
return $input[$key];
}
为了双重检查是否正常工作,检查此代码在 randomBackground 函数内的数字是否发生变化
var_dump($number, $key);
有关更多信息,请参阅缓存标签
pubmlst.theme
添加一个预处理函数来清除此特定节点类型的缓存,清理会话缓存和随机中使用的变量
function pubmlst_preprocess_node__front(&$variables){
$variables['#cache'] = [
'max-age' => 0,
'contexts' => ['session']
];
$variables['hero_rand_bg']['#cache']['max-age'] = 0;
$variables['hero_rand_test']['#cache']['max-age'] = 0;
}