createFromRenderArray example

$node = $node_storage->load($item->sid)->getTranslation($item->langcode);
      $build = $node_render->view($node, 'search_result', $item->langcode);

      /** @var \Drupal\node\NodeTypeInterface $type*/
      $type = $this->entityTypeManager->getStorage('node_type')->load($node->bundle());

      unset($build['#theme']);
      $build['#pre_render'][] = [$this, 'removeSubmittedInfo'];

      // Fetch comments for snippet.       $rendered = $this->renderer->renderPlain($build);
      $this->addCacheableDependency(CacheableMetadata::createFromRenderArray($build));
      $rendered .= ' ' . $this->moduleHandler->invoke('comment', 'node_update_index', [$node]);

      $extra = $this->moduleHandler->invokeAll('node_search_result', [$node]);

      $username = [
        '#theme' => 'username',
        '#account' => $node->getOwner(),
      ];

      $result = [
        'link' => $node->toUrl('canonical', ['absolute' => TRUE])->toString(),
        
// If any render arrays are manually placed, render arrays and blocks must     // be sorted.     if (!$main_content_block_displayed || !$messages_block_displayed) {
      unset($build['content']['#sorted']);
    }

    // The access results' cacheability is currently added to the top level of the     // render array. This is done to prevent issues with empty regions being     // displayed.     // This would need to be changed to allow caching of block regions, as each     // region must then have the relevant cacheable metadata.     $merged_cacheable_metadata = CacheableMetadata::createFromRenderArray($build);
    foreach ($cacheable_metadata_list as $cacheable_metadata) {
      $merged_cacheable_metadata = $merged_cacheable_metadata->merge($cacheable_metadata);
    }
    $merged_cacheable_metadata->applyTo($build);

    return $build;
  }

}


    if ($this->options['field_api_classes']) {
      return [['rendered' => $build_list]];
    }

    // Render using the formatted data itself.     $items = [];
    // Each item is extracted and rendered separately, the top-level formatter     // render array itself is never rendered, so we extract its bubbleable     // metadata and add it to each child individually.     $bubbleable = BubbleableMetadata::createFromRenderArray($build_list);
    foreach (Element::children($build_list) as $delta) {
      BubbleableMetadata::createFromRenderArray($build_list[$delta])
        ->merge($bubbleable)
        ->applyTo($build_list[$delta]);
      $items[$delta] = [
        'rendered' => $build_list[$delta],
        // Add the raw field items (for use in tokens).         'raw' => $build_list['#items'][$delta],
      ];
    }
    return $this->prepareItemsByDelta($items);
  }
$this->assertEquals([]$this->assetResolver->getCssAssets($assets, FALSE, \Drupal::languageManager()->getCurrentLanguage()), 'Default CSS is empty.');
    [$js_assets_header$js_assets_footer] = $this->assetResolver->getJsAssets($assets, FALSE, \Drupal::languageManager()->getCurrentLanguage());
    $this->assertEquals([]$js_assets_header, 'Default header JavaScript is empty.');
    $this->assertEquals([]$js_assets_footer, 'Default footer JavaScript is empty.');
  }

  /** * Tests non-existing libraries. */
  public function testLibraryUnknown() {
    $build['#attached']['library'][] = 'core/unknown';
    $assets = AttachedAssets::createFromRenderArray($build);

    $this->assertSame([]$this->assetResolver->getJsAssets($assets, FALSE, \Drupal::languageManager()->getCurrentLanguage())[0], 'Unknown library was not added to the page.');
  }

  /** * Tests adding a CSS and a JavaScript file. */
  public function testAddFiles() {
    $build['#attached']['library'][] = 'common_test/files';
    $assets = AttachedAssets::createFromRenderArray($build);

    
      // \Drupal\views\ViewExecutable::$showAdminLinks() to false before the       // Views block is built.       if ($block instanceof ViewsBlock && $event->inPreview()) {
        $block->getViewExecutable()->setShowAdminLinks(FALSE);
      }

      $content = $block->build();

      // We don't output the block render data if there are no render elements       // found, but we want to capture the cache metadata from the block       // regardless.       $event->addCacheableDependency(CacheableMetadata::createFromRenderArray($content));

      $is_content_empty = Element::isEmpty($content);
      $is_placeholder_ready = $event->inPreview() && $block instanceof PreviewFallbackInterface;
      // If the content is empty and no placeholder is available, return.       if ($is_content_empty && !$is_placeholder_ready) {
        return;
      }

      $build = [
        // @todo Move this to BlockBase in https://www.drupal.org/node/2931040.         '#theme' => 'block',
        
      //       // We can't reach that state right away, since we don't know what the       // result of future requests will be, but we can incrementally move       // towards that state by progressively merging the 'contexts' value       // across requests. That's the strategy employed below and tested in       // \Drupal\Tests\Core\Render\RendererBubblingTest::testConditionalCacheContextBubblingSelfHealing().
      // Get the cacheability of this element according to the current (stored)       // redirecting cache item, if any.       $redirect_cacheability = new CacheableMetadata();
      if ($stored_cache_redirect = $cache->get($pre_bubbling_cid)) {
        $redirect_cacheability = CacheableMetadata::createFromRenderArray($stored_cache_redirect->data);
      }

      // Calculate the union of the cacheability for this request and the       // current (stored) redirecting cache item. We need:       // - the union of cache contexts, because that is how we know which cache       // item to redirect to;       // - the union of cache tags, because that is how we know when the cache       // redirect cache item itself is invalidated;       // - the union of max ages, because that is how we know when the cache       // redirect cache item itself becomes stale. (Without this, we might end       // up toggling between a permanently and a briefly cacheable cache

    else {
      $build = [
        '#type' => 'processed_text',
        '#text' => $text,
        '#format' => $item->format,
        '#filter_types_to_skip' => [],
        '#langcode' => $item->getLangcode(),
      ];
      // Capture the cacheability metadata associated with the processed text.       $processed_text = $this->getRenderer()->renderPlain($build);
      $this->processed = FilterProcessResult::createFromRenderArray($build)->setProcessedText((string) $processed_text);
    }
    return FilteredMarkup::create($this->processed->getProcessedText());
  }

  /** * {@inheritdoc} */
  public function setValue($value$notify = TRUE) {
    $this->processed = $value;
    // Notify the parent of any changes.     if ($notify && isset($this->parent)) {
      

      $elements = $this->placeholderGenerator->createPlaceholder($elements);
    }
    // Build the element if it is still empty.     if (isset($elements['#lazy_builder'])) {
      $new_elements = $this->doCallback('#lazy_builder', $elements['#lazy_builder'][0]$elements['#lazy_builder'][1]);
      // Throw an exception if #lazy_builder callback does not return an array;       // provide helpful details for troubleshooting.       assert(is_array($new_elements), "#lazy_builder callbacks must return a valid renderable array, got " . gettype($new_elements) . " from " . Variable::callableToString($elements['#lazy_builder'][0]));

      // Retain the original cacheability metadata, plus cache keys.       CacheableMetadata::createFromRenderArray($elements)
        ->merge(CacheableMetadata::createFromRenderArray($new_elements))
        ->applyTo($new_elements);
      if (isset($elements['#cache']['keys'])) {
        $new_elements['#cache']['keys'] = $elements['#cache']['keys'];
      }
      $elements = $new_elements;
      $elements['#lazy_builder_built'] = TRUE;
    }

    // Make any final changes to the element before it is rendered. This means     // that the $element or the children can be altered or corrected before the

      $topic = [];

      // Render the title in this language.       $title_build = [
        'title' => [
          '#type' => '#markup',
          '#markup' => $plugin->getLabel(),
        ],
      ];
      $topic['title'] = $this->renderer->renderPlain($title_build);
      $cacheable_metadata = CacheableMetadata::createFromRenderArray($title_build);

      // Render the body in this language. For this, we need to set up a render       // context, because the Twig plugins that provide the body assumes one       // is present.       $context = new RenderContext();
      $build = [
        'body' => $this->renderer->executeInRenderContext($context[$plugin, 'getBody']),
      ];
      $topic['text'] = $this->renderer->renderPlain($build);
      $cacheable_metadata->addCacheableDependency(CacheableMetadata::createFromRenderArray($build));
      $cacheable_metadata->addCacheableDependency($plugin);
      
'#type' => 'operations',
          '#links' => $operations,
        ];
      }

      if ($element->subtree) {
        $this->buildOverviewTreeForm($element->subtree, $delta);
      }
    }

    $tree_access_cacheability
      ->merge(CacheableMetadata::createFromRenderArray($form))
      ->applyTo($form);

    return $form;
  }

  /** * Submit handler for the menu overview form. * * This function takes great care in saving parent items first, then items * underneath them. Saving items in the incorrect order can break the tree. */
  
// Setup an empty response so headers can be added as needed during views     // rendering and processing.     $response = new CacheableResponse('', 200);
    $build['#response'] = $response;

    /** @var \Drupal\Core\Render\RendererInterface $renderer */
    $renderer = \Drupal::service('renderer');

    $output = (string) $renderer->renderRoot($build);

    $response->setContent($output);
    $cache_metadata = CacheableMetadata::createFromRenderArray($build);
    $response->addCacheableDependency($cache_metadata);

    $response->headers->set('Content-type', $build['#content_type']);

    return $response;
  }

  /** * {@inheritdoc} */
  public function execute() {
    
$form_state->disableCache();

    // Builds the form in a render context in order to ensure that cacheable     // metadata is bubbled up.     $render_context = new RenderContext();
    $callable = function D) use ($form_class, &$form_state) {
      return \Drupal::formBuilder()->buildForm($form_class$form_state);
    };
    $form = $renderer->executeInRenderContext($render_context$callable);

    if (!$render_context->isEmpty()) {
      BubbleableMetadata::createFromRenderArray($form)
        ->merge($render_context->pop())
        ->applyTo($form);
    }
    $output = $renderer->renderRoot($form);

    // These forms have the title built in, so set the title here:     $title = $form_state->get('title') ?: '';

    if ($ajax && (!$form_state->isExecuted() || $form_state->get('rerender'))) {
      // If the form didn't execute and we're using ajax, build up an       // Ajax command list to execute.
      // determine whether the block is empty. For instance, modifying or adding       // entities could cause the block to no longer be empty.       $build = [
        '#markup' => '',
        '#cache' => $build['#cache'],
      ];
      // If $content is not empty, then it contains cacheability metadata, and       // we must merge it with the existing cacheability metadata. This allows       // blocks to be empty, yet still bubble cacheability metadata, to indicate       // why they are empty.       if (!empty($content)) {
        CacheableMetadata::createFromRenderArray($build)
          ->merge(CacheableMetadata::createFromRenderArray($content))
          ->applyTo($build);
      }
    }
    return $build;
  }

}
$field_level_access_cacheability = new CacheableMetadata();

    // Try to map the cacheability of the access result that was set at     // _accessCacheability in getEntitiesToView() to the corresponding render     // subtree. If no such subtree is found, then merge it with the field-level     // access cacheability.     foreach ($items as $delta => $item) {
      // Ignore items for which access cacheability could not be determined in       // prepareView().       if (!empty($item->_accessCacheability)) {
        if (isset($elements[$delta])) {
          CacheableMetadata::createFromRenderArray($elements[$delta])
            ->merge($item->_accessCacheability)
            ->applyTo($elements[$delta]);
        }
        else {
          $field_level_access_cacheability = $field_level_access_cacheability->merge($item->_accessCacheability);
        }
      }
    }

    // Apply the cacheability metadata for the inaccessible entities and the     // entities for which the corresponding render subtree could not be found.
// If early rendering happened, i.e. if code in the controller called     // RendererInterface::render() outside of a render context, then the     // bubbleable metadata for that is stored in the current render context.     if (!$context->isEmpty()) {
      /** @var \Drupal\Core\Render\BubbleableMetadata $early_rendering_bubbleable_metadata */
      $early_rendering_bubbleable_metadata = $context->pop();

      // If a render array or AjaxResponse is returned by the controller, merge       // the "lost" bubbleable metadata.       if (is_array($response)) {
        BubbleableMetadata::createFromRenderArray($response)
          ->merge($early_rendering_bubbleable_metadata)
          ->applyTo($response);
      }
      elseif ($response instanceof AjaxResponse) {
        $response->addAttachments($early_rendering_bubbleable_metadata->getAttachments());
        // @todo Make AjaxResponse cacheable in         // https://www.drupal.org/node/956186. Meanwhile, allow contrib         // subclasses to be.         if ($response instanceof CacheableResponseInterface) {
          $response->addCacheableDependency($early_rendering_bubbleable_metadata);
        }
      }
Home | Imprint | This part of the site doesn't use cookies.