renderRoot example

{$field_name}[0][value]" => $filtered_markup,
    ];
    $this->submitForm($edit, 'Save');
    preg_match('|entity_test/manage/(\d+)|', $this->getUrl()$match);
    $id = $match[1];
    $this->assertSession()->pageTextContains('entity_test ' . $id . ' has been created.');

    // Display the entity.     $entity = EntityTest::load($id);
    $display = $entity_display_repository->getViewDisplay($entity->getEntityTypeId()$entity->bundle(), 'full');
    $content = $display->build($entity);
    $rendered_entity = \Drupal::service('renderer')->renderRoot($content);
    $this->assertStringContainsString('<div><strong><span>', (string) $rendered_entity);

    // Log back in as admin.     $this->drupalLogin($this->adminUser);
    // Change field to allow only one format.     $path = "entity_test/structure/entity_test/fields/entity_test.entity_test.$field_name";
    $this->drupalGet($path);
    $this->submitForm(["settings[allowed_formats][{$format1->id()}]" => $format1->id()], 'Save settings');
    $this->drupalGet($path);
    // Display the creation form.     $this->drupalLogin($this->webUser);
    

  public function testComputedFieldHandler() {
    \Drupal::state()->set('entity_test_computed_field_item_list_value', ['computed string']);

    $entity = EntityTestComputedField::create([]);
    $entity->save();

    $view = Views::getView('computed_field_view');

    $rendered_view = $view->preview();
    $output = $this->container->get('renderer')->renderRoot($rendered_view);
    $this->assertStringContainsString('computed string', (string) $output);
  }

}
$this->resetAll();

    $cache = $this->container->get('theme.registry')->get();
    // Create array of Twig templates.     $templates = drupal_find_theme_templates($cache$extension$this->getThemePath('test_theme'));
    $templates += drupal_find_theme_templates($cache$extension$this->getModulePath('node'));

    // Create a node and test different features of the debug markup.     $node = $this->drupalCreateNode();
    $builder = \Drupal::entityTypeManager()->getViewBuilder('node');
    $build = $builder->view($node);
    $output = $renderer->renderRoot($build);
    $this->assertStringContainsString('<!-- THEME DEBUG -->', $output, 'Twig debug markup found in theme output when debug is enabled.');
    $this->assertStringContainsString("THEME HOOK: 'node'", $output, 'Theme call information found.');
    $this->assertStringContainsString('* node--1--full' . $extension . PHP_EOL . ' x node--1' . $extension . PHP_EOL . ' * node--page--full' . $extension . PHP_EOL . ' * node--page' . $extension . PHP_EOL . ' * node--full' . $extension . PHP_EOL . ' * node' . $extension$output, 'Suggested template files found in order and node ID specific template shown as current template.');
    $this->assertStringContainsString(Html::escape('node--<script type="text/javascript">alert(\'yo\');</script>')(string) $output);
    $this->assertStringContainsString('<!-- INVALID FILE NAME SUGGESTIONS:' . PHP_EOL . ' See https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Render!theme.api.php/function/hook_theme_suggestions_alter' . PHP_EOL . ' invalid_theme_suggestions' . PHP_EOL . '-->', $output, 'Twig debug markup found invalid suggestions.');
    $template_filename = $templates['node__1']['path'] . '/' . $templates['node__1']['template'] . $extension;
    $this->assertStringContainsString("BEGIN OUTPUT from '$template_filename'", $output, 'Full path to current template file found.');

    // Create another node and make sure the template suggestions shown in the     // debug markup are correct.     $node2 = $this->drupalCreateNode();
    
    $entity = EntityTest::create([
      'name' => $this->randomString(),
      $this->fieldStorage->getName() => [
        'value' => '2016-09-20',
        'end_value' => '2016-09-21',
      ],
    ]);

    // Verify the untranslated separator.     $display = EntityViewDisplay::collectRenderDisplay($entity, 'default');
    $build = $display->build($entity);
    $output = $this->container->get('renderer')->renderRoot($build);
    $this->assertStringContainsString('UNTRANSLATED', (string) $output);

    // Translate the separator.     ConfigurableLanguage::createFromLangcode('nl')->save();
    /** @var \Drupal\language\ConfigurableLanguageManagerInterface $language_manager */
    $language_manager = $this->container->get('language_manager');
    $language_manager->getLanguageConfigOverride('nl', 'core.entity_view_display.entity_test.entity_test.default')
      ->set('content.' . $this->fieldStorage->getName() . '.settings.separator', 'NL_TRANSLATED!')
      ->save();

    $this->container->get('language.config_factory_override')
      
$display->setComponent('file_test', [
      'label' => 'above',
      'type' => 'file_default',
      'weight' => 1,
    ])->save();
    $entity = EntityTest::create();
    $entity->file_test = ['entity' => $file3];
    $uri = $file3->getFileUri();
    $output = \Drupal::entityTypeManager()
      ->getViewBuilder('entity_test')
      ->view($entity, 'default');
    \Drupal::service('renderer')->renderRoot($output);
    $this->assertTrue(!empty($entity->file_test->entity));
    $this->assertEquals($uri$entity->file_test->entity->getFileUri());
  }

}
    $entity = Block::load('test_block1');
    $builder = \Drupal::entityTypeManager()->getViewBuilder('block');
    $output = $builder->view($entity, 'block');
    $expected = [];
    $expected[] = '<div id="block-test-block1">';
    $expected[] = ' ';
    $expected[] = ' ';
    $expected[] = ' ';
    $expected[] = ' </div>';
    $expected[] = '';
    $expected_output = implode("\n", $expected);
    $this->assertSame($expected_output(string) $this->renderer->renderRoot($output));

    // Reset the HTML IDs so that the next render is not affected.     Html::resetSeenIds();

    // Test the rendering of a block with a given title.     $entity = $this->controller->create([
      'id' => 'test_block2',
      'theme' => 'stark',
      'plugin' => 'test_html',
      'settings' => [
        'label' => 'Powered by Bananas',
      ],
public static function buildResponse($view_id$display_id, array $args = []) {
    $build = static::buildBasicRenderable($view_id$display_id$args);

    // Set up an empty response, so for example RSS can set the proper     // Content-Type header.     $response = new CacheableResponse('', 200);
    $build['#response'] = $response;

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

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

    if (empty($output)) {
      throw new NotFoundHttpException();
    }

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

    return $response;
  }

  
$entity->save();

    /** @var \Drupal\Core\Session\AccountSwitcherInterface $account_switcher */
    $account_switcher = \Drupal::service('account_switcher');

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

    $account_switcher->switchTo($this->userWithAccess);
    $executable = Views::getView($view_id);
    $build = $executable->preview();
    $this->setRawContent($renderer->renderRoot($build));

    $this->assertText($field_content);
    $this->assertTrue(isset($executable->field[$field_name]));

    $account_switcher->switchTo($this->userWithoutAccess);
    $executable = Views::getView($view_id);
    $build = $executable->preview();
    $this->setRawContent($renderer->renderRoot($build));

    $this->assertNoText($field_content);
    $this->assertFalse(isset($executable->field[$field_name]));

    
/** * Tests sending non-JS and AJAX requests to open and manipulate modals. */
  public function testDialog() {
    $this->drupalLogin($this->drupalCreateUser(['administer contact forms']));
    // Ensure the elements render without notices or exceptions.     $this->drupalGet('ajax-test/dialog');

    // Set up variables for this test.     $dialog_renderable = AjaxTestController::dialogContents();
    $dialog_contents = \Drupal::service('renderer')->renderRoot($dialog_renderable);

    // Check that requesting a modal dialog without JS goes to a page.     $this->drupalGet('ajax-test/dialog-contents');
    $this->assertSession()->responseContains($dialog_contents);

    // Visit the page containing the many test dialog links.     $this->drupalGet('ajax-test/dialog');

    // Tests a basic modal dialog by verifying the contents of the dialog are as     // expected.     $this->getSession()->getPage()->clickLink('Link 1 (modal)');

    
$this->assertSession()->pageTextContains('Test entity 51');
  }

  /** * Tests that the correct cache contexts are set. */
  public function testCacheContexts() {
    /** @var \Drupal\Core\Entity\EntityListBuilderInterface $list_builder */
    $list_builder = $this->container->get('entity_type.manager')->getListBuilder('entity_test');

    $build = $list_builder->render();
    $this->container->get('renderer')->renderRoot($build);

    $this->assertEqualsCanonicalizing(['entity_test_view_grants', 'languages:' . LanguageInterface::TYPE_INTERFACE, 'theme', 'url.query_args.pagers:0', 'user.permissions']$build['#cache']['contexts']);
  }

  /** * Tests if the list cache tags are set. */
  public function testCacheTags() {
    $this->drupalGet('entity_test/list');
    $this->assertSession()->responseHeaderContains('X-Drupal-Cache-Tags', 'entity_test_list');
  }

}
/** * Render an image style element. * * Function \Drupal\Core\Render\RendererInterface::render() alters the passed * $variables array by adding a new key '#printed' => TRUE. This prevents next * call to re-render the element. We wrap * \Drupal\Core\Render\RendererInterface::render() in a helper protected * method and pass each time a fresh array so that $variables won't get * altered and the element is re-rendered each time. */
  protected function getImageTag($variables) {
    return str_replace("\n", '', \Drupal::service('renderer')->renderRoot($variables));
  }

}
// Test that the default formatter is being used.     $image_uri = File::load($node->{$field_name}->target_id)->getFileUri();
    $image = [
      '#theme' => 'image',
      '#uri' => $image_uri,
      '#width' => 360,
      '#height' => 240,
      '#alt' => $alt,
      '#attributes' => ['loading' => 'lazy'],
    ];
    $default_output = str_replace("\n", '', $renderer->renderRoot($image));
    $this->assertSession()->responseContains($default_output);

    // Test field not being configured. This should not cause a fatal error.     $display_options = [
      'type' => 'responsive_image_test',
      'settings' => ResponsiveImageFormatter::defaultSettings(),
    ];
    $display = $this->container->get('entity_type.manager')
      ->getStorage('entity_view_display')
      ->load('node.article.default');
    if (!$display) {
      
/** @var \Drupal\Core\Menu\LocalActionManager $local_action_manager */
    $local_action_manager = \Drupal::service('plugin.manager.menu.local_action');
    $build = [
      '#cache' => [
        'key' => 'foo',
      ],
      $local_action_manager->getActionsForRoute('menu_test.local_action7'),
    ];

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

    $this->assertContains('menu_local_action7', $build[0]['menu_test.local_action7']['#cache']['tags']);
    $this->assertContains('url.query_args:menu_local_action7', $build[0]['menu_test.local_action7']['#cache']['contexts']);

    $this->assertContains('menu_local_action8', $build[0]['menu_test.local_action8']['#cache']['tags']);
    $this->assertContains('url.query_args:menu_local_action8', $build[0]['menu_test.local_action8']['#cache']['contexts']);

    $this->assertContains('menu_local_action7', $build['#cache']['tags']);
    $this->assertContains('url.query_args:menu_local_action7', $build['#cache']['contexts']);

    $this->assertContains('menu_local_action8', $build['#cache']['tags']);
    
$renderer = $this->container->get('renderer');
    $view = Views::getView('test_field_classes');
    $view->initHandlers();

    // Tests whether the default field classes are added.     $id_field = $view->field['id'];

    $id_field->options['element_default_classes'] = FALSE;
    // Setup some kind of label by default.     $id_field->options['label'] = $this->randomMachineName();
    $output = $view->preview();
    $output = $renderer->renderRoot($output);
    $this->assertEmpty($this->xpathContent($output, '//div[contains(@class, :class)]', [':class' => 'field-content']));
    $this->assertEmpty($this->xpathContent($output, '//div[contains(@class, :class)]', [':class' => 'field__label']));

    $id_field->options['element_default_classes'] = TRUE;
    $output = $view->preview();
    $output = $renderer->renderRoot($output);
    // Per default the label and the element of the field are spans.     $this->assertNotEmpty($this->xpathContent($output, '//span[contains(@class, :class)]', [':class' => 'field-content']));
    $this->assertNotEmpty($this->xpathContent($output, '//span[contains(@class, :class)]', [':class' => 'views-label']));
    $this->assertNotEmpty($this->xpathContent($output, '//div[contains(@class, :class)]', [':class' => 'views-field']));

    
$view->save();

    /** @var \Drupal\Core\Session\AccountSwitcherInterface $account_switcher */
    $account_switcher = \Drupal::service('account_switcher');

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

    $account_switcher->switchTo($this->adminUser);
    $executable = Views::getView($view_id);
    $build = $executable->preview();
    $this->setRawContent($renderer->renderRoot($build));

    $this->assertLink('My comment title');
    $this->assertLink('Anonymous comment title');
    // Display plugin of the view is showing the name field. When comment     // belongs to an authenticated user the name field has no value.     $comment_author = $this->xpath('//div[contains(@class, :class)]/span[normalize-space(text())=""]', [
      ':class' => 'views-field-subject',
    ]);
    $this->assertNotEmpty($comment_author);
    // When comment belongs to an anonymous user the name field has a value and     // it is rendered correctly.
Home | Imprint | This part of the site doesn't use cookies.