【问题标题】:Drupal 8 issue with caching render array缓存渲染数组的 Drupal 8 问题
【发布时间】:2017-11-21 16:18:11
【问题描述】:

drupal 8 有问题。我正在尝试以这种方式缓存渲染数组:

$meetingsView = [
    '#theme' => 'meetings_view',
    '#meetings_view' => $meetings,
    '#months' => $this->monthsArray,
    '#sidebar' => [
    '#theme' => 'meetings_sidebar',
        '#search_meetings_form' => $searchMeetingsForm,
    ],
    '#language' => $language,
    '#children' => $meetingRows,
    '#attached' => [
        'library' => [
            'my_module/my_module',
        ],
        'drupalSettings' => [
            'siteUrl' => $base_url,
        ],
    ],
    '#cache' => [
        'keys' => ['meeting_views'],
        'context' => [],
        'tags' => ['http_response'],
        'max-age' => 60,
    ],
];

我在绑定到路由的控制器方法结束时返回它以查看会议列表。

遗憾的是,该页面从未使用我的 max-age(60 秒)。

当我使用时

$cacheMetadata = new CacheableMetadata();
$cacheMetadata->setCacheContexts([]);
$cacheMetadata->setCacheMaxAge(60);
$cacheMetadata->setCacheTags([]);

$markup = $renderer->renderRoot($meetingsView);

$response = new HtmlResponse($markup, Response::HTTP_OK);
$response->addCacheableDependency($cacheMetadata);

并返回响应,页面缓存成功,max-age很好,但没有使用主题模板,因此出现没有样式和页面标记。

您能否帮我找到解决方案:要么成功缓存渲染数组,要么成功在我的主题中渲染响应。

最好的,

PF

【问题讨论】:

  • 我想我可能已经找到了解决方案。在渲染数组中,您必须缓存每个子元素(#children),这意味着在渲染数组中为渲染数组的每一级创建一个缓存数组。因此,我根据查询参数和级别(在循环内)创建了一个 cacheID,并将这个 cid 用作缓存键。 $cid = 'api:' . \Drupal::languageManager()->getCurrentLanguage()->getId() . ':meetings:' . http_build_query($parameters, '', ':'); 用于父数组,例如。我会在进行更多测试时保持更新。
  • 一切正常。我的最后一个问题是从表单提交调用的同一页面不缓存。我会调查的。

标签: caching drupal-8


【解决方案1】:

我想我可能已经找到了解决方案。在渲染数组中,您必须缓存每个子元素(#children),这意味着在渲染数组中为渲染数组的每一级创建一个缓存数组。因此,我根据查询参数和级别(在循环内)创建了一个 cacheID,并将这个 cid 用作缓存键。

$cid = 'api:' . \Drupal::languageManager()->getCurrentLanguage()->getId() . ':meetings:' . http_build_query($parameters, '', ':');

以父数组为例。

'#cache' => [
  'keys' => [$cid],
  'context' => [],
  'tags' => ['http_response'],
  'max-age' => $cache_expire,
],

在孩子们身上

'#cache' => [
  'keys' => [
    $cid,
    'meeting_rows:' . $i,
  ],
  'context' => [],
  'tags' => ['http_response'],
  'max-age' => $cache_expire,
],

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-20
    • 1970-01-01
    • 2021-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多