我想配置我的 Drupal 8 网站,以便任何时候使用查询参数“refcode”访问我的网站时,该值都会复制到该页面上的所有菜单链接上。例如,使用 https://www.example.com?refcode=joe会将“?refcode=joe”添加到该页面上的所有菜单链接。一旦有人使用特定的引用代码进入网站,那么使用菜单链接在网站中导航将保留该引用代码,而使用菜单链接导航离开网站也会在外部菜单链接上保留该引用代码。
当缓存为空时,此代码有效:
function mymodule_link_alter( &$variables )
{
if ( $refcode = \Drupal::request( )->query->get( 'refcode' ) )
$variables['options']['query']['refcode'] = $refcode;
}
当页面被缓存时,它不会。我尝试添加这个:
$variables['#cache']['contexts'][] = 'url.query_args:refcode';
但这不起作用。我想我必须在其他地方添加这个缓存指令,但我不知道在哪里。是否有地方可以指示 Drupal 8 在检索任何缓存页面时考虑“refcode”?
最佳答案
我终于明白了这一点。我必须确定哪些 block 类型和哪些节点类型可能引用 refcode 查询参数并更新它们的缓存设置:
function mymodule_preprocess_block( &$variables )
{
if ( $variables['base_plugin_id'] == 'system_menu_block' )
$variables['#cache']['contexts'][] = 'url.query_args:refcode';
}
function mymodule_preprocess_node( &$variables )
{
if ( $variables['node']->bundle( ) == 'main' )
$variables['#cache']['contexts'][] = 'url.query_args:refcode';
}
关于caching - 在哪里指定对所有页面进行操作的缓存上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59775111/