• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

PHP Render\BubbleableMetadata类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了PHP中Drupal\Core\Render\BubbleableMetadata的典型用法代码示例。如果您正苦于以下问题:PHP BubbleableMetadata类的具体用法?PHP BubbleableMetadata怎么用?PHP BubbleableMetadata使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了BubbleableMetadata类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的PHP代码示例。

示例1: processOutbound

 /**
  * {@inheritdoc}
  */
 public function processOutbound($route_name, Route $route, array &$parameters, BubbleableMetadata $bubbleable_metadata = NULL)
 {
     if ($route_name === '<current>') {
         if ($current_route = $this->routeMatch->getRouteObject()) {
             $requirements = $current_route->getRequirements();
             // Setting _method and _schema is deprecated since 2.7. Using
             // setMethods() and setSchemes() are now the recommended ways.
             unset($requirements['_method']);
             unset($requirements['_schema']);
             $route->setRequirements($requirements);
             $route->setPath($current_route->getPath());
             $route->setSchemes($current_route->getSchemes());
             $route->setMethods($current_route->getMethods());
             $route->setOptions($current_route->getOptions());
             $route->setDefaults($current_route->getDefaults());
             $parameters = array_merge($parameters, $this->routeMatch->getRawParameters()->all());
             if ($bubbleable_metadata) {
                 $bubbleable_metadata->addCacheContexts(['route']);
             }
         } else {
             // If we have no current route match available, point to the frontpage.
             $route->setPath('/');
         }
     }
 }
开发者ID:aWEBoLabs,项目名称:taxi,代码行数:28,代码来源:RouteProcessorCurrent.php


示例2: providerTestCreateFromRenderArray

 /**
  * Provides test data for createFromRenderArray().
  *
  * @return array
  */
 public function providerTestCreateFromRenderArray()
 {
     $data = [];
     $empty_metadata = new BubbleableMetadata();
     $nonempty_metadata = new BubbleableMetadata();
     $nonempty_metadata->setCacheContexts(['qux'])->setCacheTags(['foo:bar'])->setAssets(['settings' => ['foo' => 'bar']]);
     $empty_render_array = [];
     $nonempty_render_array = ['#cache' => ['contexts' => ['qux'], 'tags' => ['foo:bar'], 'max-age' => Cache::PERMANENT], '#attached' => ['settings' => ['foo' => 'bar']], '#post_render_cache' => []];
     $data[] = [$empty_render_array, $empty_metadata];
     $data[] = [$nonempty_render_array, $nonempty_metadata];
     return $data;
 }
开发者ID:Nikola-xiii,项目名称:d8intranet,代码行数:17,代码来源:BubbleableMetadataTest.php


示例3: processOutbound

 public function processOutbound($path, &$options = array(), Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL)
 {
     if (array_key_exists('purl_context', $options) && $options['purl_context'] == false) {
         if (count($this->matchedModifiers->getMatched()) && $bubbleable_metadata) {
             $cacheContexts = $bubbleable_metadata->getCacheContexts();
             $cacheContexts[] = 'purl';
             $bubbleable_metadata->setCacheContexts($cacheContexts);
         }
         return $this->contextHelper->processOutbound($this->matchedModifiers->createContexts(Context::EXIT_CONTEXT), $path, $options, $request, $bubbleable_metadata);
     }
     return $this->contextHelper->processOutbound($this->matchedModifiers->createContexts(), $path, $options, $request, $bubbleable_metadata);
 }
开发者ID:activelamp,项目名称:purl-d8,代码行数:12,代码来源:PurlContextOutboundPathProcessor.php


示例4: processOutbound

 /**
  * Implements Drupal\Core\PathProcessor\OutboundPathProcessorInterface::processOutbound().
  */
 public function processOutbound($path, &$options = array(), Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL)
 {
     // Rewrite user/uid to user/username.
     if (preg_match('!^/user/([0-9]+)(/.*)?!', $path, $matches)) {
         if ($account = User::load($matches[1])) {
             $matches += array(2 => '');
             $path = '/user/' . $account->getUsername() . $matches[2];
             if ($bubbleable_metadata) {
                 $bubbleable_metadata->addCacheTags($account->getCacheTags());
             }
         }
     }
     // Rewrite forum/ to community/.
     return preg_replace('@^/forum(.*)@', '/community$1', $path);
 }
开发者ID:HakS,项目名称:drupal8_training,代码行数:18,代码来源:PathProcessorTest.php


示例5: processLinkitAutocomplete

  /**
   * Adds linkit custom autocomplete functionality to elements.
   *
   * Instead of using the core autocomplete, we use our own.
   *
   * {@inheritdoc}
   *
   * @see \Drupal\Core\Render\Element\FormElement::processAutocomplete
   */
  public static function processLinkitAutocomplete(&$element, FormStateInterface $form_state, &$complete_form) {
    $url = NULL;
    $access = FALSE;

    if (!empty($element['#autocomplete_route_name'])) {
      $parameters = isset($element['#autocomplete_route_parameters']) ? $element['#autocomplete_route_parameters'] : array();
      $url = Url::fromRoute($element['#autocomplete_route_name'], $parameters)->toString(TRUE);
      /** @var \Drupal\Core\Access\AccessManagerInterface $access_manager */
      $access_manager = \Drupal::service('access_manager');
      $access = $access_manager->checkNamedRoute($element['#autocomplete_route_name'], $parameters, \Drupal::currentUser(), TRUE);
    }

    if ($access) {
      $metadata = BubbleableMetadata::createFromRenderArray($element);
      if ($access->isAllowed()) {
        $element['#attributes']['class'][] = 'form-linkit-autocomplete';
        $metadata->addAttachments(['library' => ['linkit/linkit.autocomplete']]);
        // Provide a data attribute for the JavaScript behavior to bind to.
        $element['#attributes']['data-autocomplete-path'] = $url->getGeneratedUrl();
        $metadata = $metadata->merge($url);
      }
      $metadata
        ->merge(BubbleableMetadata::createFromObject($access))
        ->applyTo($element);
    }

    return $element;
  }
开发者ID:eloiv,项目名称:botafoc.cat,代码行数:37,代码来源:Linkit.php


示例6: testTokenReplacement

 /**
  * Tests core token replacements generated from a view.
  */
 function testTokenReplacement()
 {
     $token_handler = \Drupal::token();
     $view = Views::getView('test_tokens');
     $view->setDisplay('page_1');
     $this->executeView($view);
     $expected = array('[view:label]' => 'Test tokens', '[view:description]' => 'Test view to token replacement tests.', '[view:id]' => 'test_tokens', '[view:title]' => 'Test token page', '[view:url]' => $view->getUrl(NULL, 'page_1')->setAbsolute(TRUE)->toString(), '[view:total-rows]' => (string) $view->total_rows, '[view:base-table]' => 'views_test_data', '[view:base-field]' => 'id', '[view:items-per-page]' => '10', '[view:current-page]' => '1', '[view:page-count]' => '1');
     $base_bubbleable_metadata = BubbleableMetadata::createFromObject($view->storage);
     $metadata_tests = [];
     $metadata_tests['[view:label]'] = $base_bubbleable_metadata;
     $metadata_tests['[view:description]'] = $base_bubbleable_metadata;
     $metadata_tests['[view:id]'] = $base_bubbleable_metadata;
     $metadata_tests['[view:title]'] = $base_bubbleable_metadata;
     $metadata_tests['[view:url]'] = $base_bubbleable_metadata;
     $metadata_tests['[view:total-rows]'] = $base_bubbleable_metadata;
     $metadata_tests['[view:base-table]'] = $base_bubbleable_metadata;
     $metadata_tests['[view:base-field]'] = $base_bubbleable_metadata;
     $metadata_tests['[view:items-per-page]'] = $base_bubbleable_metadata;
     $metadata_tests['[view:current-page]'] = $base_bubbleable_metadata;
     $metadata_tests['[view:page-count]'] = $base_bubbleable_metadata;
     foreach ($expected as $token => $expected_output) {
         $bubbleable_metadata = new BubbleableMetadata();
         $output = $token_handler->replace($token, array('view' => $view), [], $bubbleable_metadata);
         $this->assertIdentical($output, $expected_output, format_string('Token %token replaced correctly.', array('%token' => $token)));
         $this->assertEqual($bubbleable_metadata, $metadata_tests[$token]);
     }
 }
开发者ID:sojo,项目名称:d8_friendsofsilence,代码行数:30,代码来源:TokenReplaceTest.php


示例7: testSystemSiteTokenReplacement

 /**
  * Tests the generation of all system site information tokens.
  */
 public function testSystemSiteTokenReplacement()
 {
     $url_options = array('absolute' => TRUE, 'language' => $this->interfaceLanguage);
     $slogan = '<blink>Slogan</blink>';
     $safe_slogan = Xss::filterAdmin($slogan);
     // Set a few site variables.
     $config = $this->config('system.site');
     $config->set('name', '<strong>Drupal<strong>')->set('slogan', $slogan)->set('mail', '[email protected]')->save();
     // Generate and test tokens.
     $tests = array();
     $tests['[site:name]'] = Html::escape($config->get('name'));
     $tests['[site:slogan]'] = $safe_slogan;
     $tests['[site:mail]'] = $config->get('mail');
     $tests['[site:url]'] = \Drupal::url('<front>', [], $url_options);
     $tests['[site:url-brief]'] = preg_replace(array('!^https?://!', '!/$!'), '', \Drupal::url('<front>', [], $url_options));
     $tests['[site:login-url]'] = \Drupal::url('user.page', [], $url_options);
     $base_bubbleable_metadata = new BubbleableMetadata();
     $metadata_tests = [];
     $metadata_tests['[site:name]'] = BubbleableMetadata::createFromObject(\Drupal::config('system.site'));
     $metadata_tests['[site:slogan]'] = BubbleableMetadata::createFromObject(\Drupal::config('system.site'));
     $metadata_tests['[site:mail]'] = BubbleableMetadata::createFromObject(\Drupal::config('system.site'));
     $bubbleable_metadata = clone $base_bubbleable_metadata;
     $metadata_tests['[site:url]'] = $bubbleable_metadata->addCacheContexts(['url.site']);
     $metadata_tests['[site:url-brief]'] = $bubbleable_metadata;
     $metadata_tests['[site:login-url]'] = $bubbleable_metadata;
     // Test to make sure that we generated something for each token.
     $this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
     foreach ($tests as $input => $expected) {
         $bubbleable_metadata = new BubbleableMetadata();
         $output = $this->tokenService->replace($input, array(), array('langcode' => $this->interfaceLanguage->getId()), $bubbleable_metadata);
         $this->assertEqual($output, $expected, new FormattableMarkup('System site information token %token replaced.', ['%token' => $input]));
         $this->assertEqual($bubbleable_metadata, $metadata_tests[$input]);
     }
 }
开发者ID:aWEBoLabs,项目名称:taxi,代码行数:37,代码来源:TokenReplaceKernelTest.php


示例8: filter

 /**
  * {@inheritdoc}
  */
 public function filter(DataDefinitionInterface $definition, $value, array $arguments, BubbleableMetadata $bubbleable_metadata = NULL)
 {
     if ($definition->getDataType() != 'timestamp') {
         // Convert the date to an timestamp.
         $value = $this->getTypedDataManager()->create($definition, $value)->getDateTime()->getTimestamp();
     }
     $arguments += [0 => 'medium', 1 => '', 2 => NULL, 3 => NULL];
     if ($arguments[0] != 'custom' && $bubbleable_metadata) {
         $config = $this->dateFormatStorage->load($arguments[0]);
         if (!$config) {
             throw new \InvalidArgumentException("Unknown date format {$arguments['0']} given.");
         }
         $bubbleable_metadata->addCacheableDependency($config);
     }
     return $this->dateFormatter->format($value, $arguments[0], $arguments[1], $arguments[2], $arguments[3]);
 }
开发者ID:Progressable,项目名称:openway8,代码行数:19,代码来源:FormatDateFilter.php


示例9: build

 /**
  * {@inheritdoc}
  */
 public function build()
 {
     // Grab test attachment fixtures from
     // Drupal\render_attached_test\Controller\RenderAttachedTestController.
     $controller = new RenderAttachedTestController();
     $attached = BubbleableMetadata::mergeAttachments($controller->feed(), $controller->head());
     $attached = BubbleableMetadata::mergeAttachments($attached, $controller->header());
     $attached = BubbleableMetadata::mergeAttachments($attached, $controller->teapotHeaderStatus());
     // Return some arbitrary markup so the block doesn't disappear.
     $attached['#markup'] = 'Markup from attached_rendering_block.';
     return $attached;
 }
开发者ID:HakS,项目名称:drupal8_training,代码行数:15,代码来源:AttachedRenderingBlock.php


示例10: build

 /**
  * {@inheritdoc}
  */
 public function build()
 {
     // Grab test attachment fixtures from
     // Drupal\render_attached_test\Controller\TestController.
     $controller = new TestController();
     $attached = BubbleableMetadata::mergeAttachments($controller->feed(), $controller->head());
     $attached = BubbleableMetadata::mergeAttachments($attached, $controller->header());
     $attached = BubbleableMetadata::mergeAttachments($attached, $controller->teapotHeaderStatus());
     // Use drupal_process_attached() to attach all the #attached stuff.
     drupal_process_attached($attached);
     // Return some arbitrary markup so the block doesn't disappear.
     return ['#markup' => 'Headers handled by drupal_process_attached().'];
 }
开发者ID:komejo,项目名称:article-test,代码行数:16,代码来源:DrupalProcessAttachedBlock.php


示例11: processOutbound

 /**
  * {@inheritdoc}
  */
 public function processOutbound($route_name, Route $route, array &$parameters, BubbleableMetadata $bubbleable_metadata = NULL)
 {
     if ($route->hasRequirement('_csrf_token')) {
         $path = ltrim($route->getPath(), '/');
         // Replace the path parameters with values from the parameters array.
         foreach ($parameters as $param => $value) {
             $path = str_replace("{{$param}}", $value, $path);
         }
         // Adding this to the parameters means it will get merged into the query
         // string when the route is compiled.
         if (!$bubbleable_metadata) {
             $parameters['token'] = $this->csrfToken->get($path);
         } else {
             // Generate a placeholder and a render array to replace it.
             $placeholder = hash('sha1', $path);
             $placeholder_render_array = ['#lazy_builder' => ['route_processor_csrf:renderPlaceholderCsrfToken', [$path]]];
             // Instead of setting an actual CSRF token as the query string, we set
             // the placeholder, which will be replaced at the very last moment. This
             // ensures links with CSRF tokens don't break cacheability.
             $parameters['token'] = $placeholder;
             $bubbleable_metadata->addAttachments(['placeholders' => [$placeholder => $placeholder_render_array]]);
         }
     }
 }
开发者ID:aWEBoLabs,项目名称:taxi,代码行数:27,代码来源:RouteProcessorCsrf.php


示例12: addCommand

 /**
  * Add an AJAX command to the response.
  *
  * @param \Drupal\Core\Ajax\CommandInterface $command
  *   An AJAX command object implementing CommandInterface.
  * @param bool $prepend
  *   A boolean which determines whether the new command should be executed
  *   before previously added commands. Defaults to FALSE.
  *
  * @return AjaxResponse
  *   The current AjaxResponse.
  */
 public function addCommand(CommandInterface $command, $prepend = FALSE)
 {
     if ($prepend) {
         array_unshift($this->commands, $command->render());
     } else {
         $this->commands[] = $command->render();
     }
     if ($command instanceof CommandWithAttachedAssetsInterface) {
         $assets = $command->getAttachedAssets();
         $attachments = ['library' => $assets->getLibraries(), 'drupalSettings' => $assets->getSettings()];
         $attachments = BubbleableMetadata::mergeAttachments($this->getAttachments(), $attachments);
         $this->setAttachments($attachments);
     }
     return $this;
 }
开发者ID:papillon-cendre,项目名称:d8,代码行数:27,代码来源:AjaxResponse.php


示例13: hook_tokens

/**
 * Provide replacement values for placeholder tokens.
 *
 * This hook is invoked when someone calls
 * \Drupal\Core\Utility\Token::replace(). That function first scans the text for
 * [type:token] patterns, and splits the needed tokens into groups by type.
 * Then hook_tokens() is invoked on each token-type group, allowing your module
 * to respond by providing replacement text for any of the tokens in the group
 * that your module knows how to process.
 *
 * A module implementing this hook should also implement hook_token_info() in
 * order to list its available tokens on editing screens.
 *
 * @param $type
 *   The machine-readable name of the type (group) of token being replaced, such
 *   as 'node', 'user', or another type defined by a hook_token_info()
 *   implementation.
 * @param $tokens
 *   An array of tokens to be replaced. The keys are the machine-readable token
 *   names, and the values are the raw [type:token] strings that appeared in the
 *   original text.
 * @param array $data
 *   An associative array of data objects to be used when generating replacement
 *   values, as supplied in the $data parameter to
 *  \Drupal\Core\Utility\Token::replace().
 * @param array $options
 *   An associative array of options for token replacement; see
 *   \Drupal\Core\Utility\Token::replace() for possible values.
 * @param \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata
 *   The bubbleable metadata. Prior to invoking this hook,
 *   \Drupal\Core\Utility\Token::generate() collects metadata for all of the
 *   data objects in $data. For any data sources not in $data, but that are
 *   used by the token replacement logic, such as global configuration (e.g.,
 *   'system.site') and related objects (e.g., $node->getOwner()),
 *   implementations of this hook must add the corresponding metadata.
 *   For example:
 *   @code
 *     $bubbleable_metadata->addCacheableDependency(\Drupal::config('system.site'));
 *     $bubbleable_metadata->addCacheableDependency($node->getOwner());
 *   @endcode
 *
 *   Additionally, implementations of this hook, must forward
 *   $bubbleable_metadata to the chained tokens that they invoke.
 *   For example:
 *   @code
 *     if ($created_tokens = $token_service->findWithPrefix($tokens, 'created')) {
 *       $replacements = $token_service->generate('date', $created_tokens, array('date' => $node->getCreatedTime()), $options, $bubbleable_metadata);
 *     }
 *   @endcode
 *
 * @return array
 *   An associative array of replacement values, keyed by the raw [type:token]
 *   strings from the original text.
 *
 * @see hook_token_info()
 * @see hook_tokens_alter()
 */
function hook_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata)
{
    $token_service = \Drupal::token();
    $url_options = array('absolute' => TRUE);
    if (isset($options['langcode'])) {
        $url_options['language'] = \Drupal::languageManager()->getLanguage($options['langcode']);
        $langcode = $options['langcode'];
    } else {
        $langcode = NULL;
    }
    $sanitize = !empty($options['sanitize']);
    $replacements = array();
    if ($type == 'node' && !empty($data['node'])) {
        /** @var \Drupal\node\NodeInterface $node */
        $node = $data['node'];
        foreach ($tokens as $name => $original) {
            switch ($name) {
                // Simple key values on the node.
                case 'nid':
                    $replacements[$original] = $node->nid;
                    break;
                case 'title':
                    $replacements[$original] = $sanitize ? Html::escape($node->getTitle()) : $node->getTitle();
                    break;
                case 'edit-url':
                    $replacements[$original] = $node->url('edit-form', $url_options);
                    break;
                    // Default values for the chained tokens handled below.
                // Default values for the chained tokens handled below.
                case 'author':
                    $account = $node->getOwner() ? $node->getOwner() : User::load(0);
                    $replacements[$original] = $sanitize ? Html::escape($account->label()) : $account->label();
                    $bubbleable_metadata->addCacheableDependency($account);
                    break;
                case 'created':
                    $replacements[$original] = format_date($node->getCreatedTime(), 'medium', '', NULL, $langcode);
                    break;
            }
        }
        if ($author_tokens = $token_service->findWithPrefix($tokens, 'author')) {
            $replacements = $token_service->generate('user', $author_tokens, array('user' => $node->getOwner()), $options, $bubbleable_metadata);
        }
        if ($created_tokens = $token_service->findWithPrefix($tokens, 'created')) {
//.........这里部分代码省略.........
开发者ID:ravindrasingh22,项目名称:Drupal-8-rc,代码行数:101,代码来源:token.api.php


示例14: preRenderLink

 /**
  * Pre-render callback: Renders a link into #markup.
  *
  * Doing so during pre_render gives modules a chance to alter the link parts.
  *
  * @param array $element
  *   A structured array whose keys form the arguments to
  *   \Drupal\Core\Utility\LinkGeneratorInterface::generate():
  *   - #title: The link text.
  *   - #url: The URL info either pointing to a route or a non routed path.
  *   - #options: (optional) An array of options to pass to the link generator.
  *
  * @return array
  *   The passed-in element containing a rendered link in '#markup'.
  */
 public static function preRenderLink($element)
 {
     // By default, link options to pass to the link generator are normally set
     // in #options.
     $element += array('#options' => array());
     // However, within the scope of renderable elements, #attributes is a valid
     // way to specify attributes, too. Take them into account, but do not override
     // attributes from #options.
     if (isset($element['#attributes'])) {
         $element['#options'] += array('attributes' => array());
         $element['#options']['attributes'] += $element['#attributes'];
     }
     // This #pre_render callback can be invoked from inside or outside of a Form
     // API context, and depending on that, a HTML ID may be already set in
     // different locations. #options should have precedence over Form API's #id.
     // #attributes have been taken over into #options above already.
     if (isset($element['#options']['attributes']['id'])) {
         $element['#id'] = $element['#options']['attributes']['id'];
     } elseif (isset($element['#id'])) {
         $element['#options']['attributes']['id'] = $element['#id'];
     }
     // Conditionally invoke self::preRenderAjaxForm(), if #ajax is set.
     if (isset($element['#ajax']) && !isset($element['#ajax_processed'])) {
         // If no HTML ID was found above, automatically create one.
         if (!isset($element['#id'])) {
             $element['#id'] = $element['#options']['attributes']['id'] = HtmlUtility::getUniqueId('ajax-link');
         }
         $element = static::preRenderAjaxForm($element);
     }
     if (!empty($element['#url']) && $element['#url'] instanceof CoreUrl) {
         $options = NestedArray::mergeDeep($element['#url']->getOptions(), $element['#options']);
         /** @var \Drupal\Core\Utility\LinkGenerator $link_generator */
         $link_generator = \Drupal::service('link_generator');
         $generated_link = $link_generator->generate($element['#title'], $element['#url']->setOptions($options));
         $element['#markup'] = $generated_link->getGeneratedLink();
         $generated_link->merge(BubbleableMetadata::createFromRenderArray($element))->applyTo($element);
     }
     return $element;
 }
开发者ID:HakS,项目名称:drupal8_training,代码行数:54,代码来源:Link.php


示例15: processOutbound

 /**
  * {@inheritdoc}
  */
 public function processOutbound($path, &$options = array(), Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL)
 {
     if ($request) {
         // The following values are not supposed to change during a single page
         // request processing.
         if (!isset($this->queryRewrite)) {
             if ($this->currentUser->isAnonymous()) {
                 $languages = $this->languageManager->getLanguages();
                 $config = $this->config->get('language.negotiation')->get('session');
                 $this->queryParam = $config['parameter'];
                 $this->queryValue = $request->query->has($this->queryParam) ? $request->query->get($this->queryParam) : NULL;
                 $this->queryRewrite = isset($languages[$this->queryValue]);
             } else {
                 $this->queryRewrite = FALSE;
             }
         }
         // If the user is anonymous, the user language negotiation method is
         // enabled, and the corresponding option has been set, we must preserve
         // any explicit user language preference even with cookies disabled.
         if ($this->queryRewrite) {
             if (isset($options['query']) && is_string($options['query'])) {
                 $query = array();
                 parse_str($options['query'], $query);
                 $options['query'] = $query;
             }
             if (!isset($options['query'][$this->queryParam])) {
                 $options['query'][$this->queryParam] = $this->queryValue;
             }
             if ($bubbleable_metadata) {
                 // Cached URLs that have been processed by this outbound path
                 // processor must be:
                 $bubbleable_metadata->addCacheTags($this->config->get('language.negotiation')->getCacheTags())->addCacheContexts(['url.query_args:' . $this->queryParam]);
             }
         }
     }
     return $path;
 }
开发者ID:nsp15,项目名称:Drupal8,代码行数:40,代码来源:LanguageNegotiationSession.php


示例16: ajaxFormWrapper

 /**
  * Wrapper for handling AJAX forms.
  *
  * Wrapper around \Drupal\Core\Form\FormBuilderInterface::buildForm() to
  * handle some AJAX stuff automatically.
  * This makes some assumptions about the client.
  *
  * @param \Drupal\Core\Form\FormInterface|string $form_class
  *   The value must be one of the following:
  *   - The name of a class that implements \Drupal\Core\Form\FormInterface.
  *   - An instance of a class that implements \Drupal\Core\Form\FormInterface.
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *   The current state of the form.
  *
  * @return \Drupal\Core\Ajax\AjaxResponse|string|array
  *   Returns one of three possible values:
  *   - A \Drupal\Core\Ajax\AjaxResponse object.
  *   - The rendered form, as a string.
  *   - A render array with the title in #title and the rendered form in the
  *   #markup array.
  */
 protected function ajaxFormWrapper($form_class, FormStateInterface &$form_state)
 {
     /** @var \Drupal\Core\Render\RendererInterface $renderer */
     $renderer = \Drupal::service('renderer');
     // This won't override settings already in.
     if (!$form_state->has('rerender')) {
         $form_state->set('rerender', FALSE);
     }
     $ajax = $form_state->get('ajax');
     // Do not overwrite if the redirect has been disabled.
     if (!$form_state->isRedirectDisabled()) {
         $form_state->disableRedirect($ajax);
     }
     $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 () 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);
     drupal_process_attached($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.
         $response = new AjaxResponse();
         // Attach the library necessary for using the OpenModalDialogCommand and
         // set the attachments for this Ajax response.
         $form['#attached']['library'][] = 'core/drupal.dialog.ajax';
         $response->setAttachments($form['#attached']);
         $display = '';
         $status_messages = array('#type' => 'status_messages');
         if ($messages = $renderer->renderRoot($status_messages)) {
             $display = '<div class="views-messages">' . $messages . '</div>';
         }
         $display .= $output;
         $options = array('dialogClass' => 'views-ui-dialog', 'width' => '75%');
         $response->addCommand(new OpenModalDialogCommand($title, $display, $options));
         if ($section = $form_state->get('#section')) {
             $response->addCommand(new Ajax\HighlightCommand('.' . Html::cleanCssIdentifier($section)));
         }
         return $response;
     }
     return $title ? ['#title' => $title, '#markup' => $output] : $output;
 }
开发者ID:nsp15,项目名称:Drupal8,代码行数:72,代码来源:ViewsFormBase.php


示例17: renderPlaceholders

 /**
  * Renders placeholders (#attached['placeholders']).
  *
  * First, the HTML response object is converted to an equivalent render array,
  * with #markup being set to the response's content and #attached being set to
  * the response's attachments. Among these attachments, there may be
  * placeholders that need to be rendered (replaced).
  *
  * Next, RendererInterface::renderRoot() is called, which renders the
  * placeholders into their final markup.
  *
  * The markup that results from RendererInterface::renderRoot() is now the
  * original HTML response's content, but with the placeholders rendered. We
  * overwrite the existing content in the original HTML response object with
  * this markup. The markup that was rendered for the placeholders may also
  * have attachments (e.g. for CSS/JS assets) itself, and cacheability metadata
  * that indicates what that markup depends on. That metadata is also added to
  * the HTML response object.
  *
  * @param \Drupal\Core\Render\HtmlResponse $response
  *   The HTML response whose placeholders are being replaced.
  *
  * @return \Drupal\Core\Render\HtmlResponse
  *   The updated HTML response, with replaced placeholders.
  *
  * @see \Drupal\Core\Render\Renderer::replacePlaceholders()
  * @see \Drupal\Core\Render\Renderer::renderPlaceholder()
  */
 protected function renderPlaceholders(HtmlResponse $response)
 {
     $build = ['#markup' => Markup::create($response->getContent()), '#attached' => $response->getAttachments()];
     // RendererInterface::renderRoot() renders the $build render array and
     // updates it in place. We don't care about the return value (which is just
     // $build['#markup']), but about the resulting render array.
     // @todo Simplify this when https://www.drupal.org/node/2495001 lands.
     $this->renderer->renderRoot($build);
     // Update the Response object now that the placeholders have been rendered.
     $placeholders_bubbleable_metadata = BubbleableMetadata::createFromRenderArray($build);
     $response->setContent($build['#markup'])->addCacheableDependency($placeholders_bubbleable_metadata)->setAttachments($placeholders_bubbleable_metadata->getAttachments());
     return $response;
 }
开发者ID:papillon-cendre,项目名称:d8,代码行数:41,代码来源:HtmlResponseAttachmentsProcessor.php


示例18: bubbleArgMetadata

 /**
  * Bubbles Twig template argument's cacheability & attachment metadata.
  *
  * For example: a generated link or generated URL object is passed as a Twig
  * template argument, and its bubbleable metadata must be bubbled.
  *
  * @see \Drupal\Core\GeneratedLink
  * @see \Drupal\Core\GeneratedUrl
  *
  * @param mixed $arg
  *   A Twig template argument that is about to be printed.
  *
  * @see \Drupal\Core\Theme\ThemeManager::render()
  * @see \Drupal\Core\Render\RendererInterface::render()
  */
 protected function bubbleArgMetadata($arg)
 {
     // If it's a renderable, then it'll be up to the generated render array it
     // returns to contain the necessary cacheability & attachment metadata. If
     // it doesn't implement CacheableDependencyInterface or AttachmentsInterface
     // then there is nothing to do here.
     if ($arg instanceof RenderableInterface || !($arg instanceof CacheableDependencyInterface || $arg instanceof AttachmentsInterface)) {
         return;
     }
     $arg_bubbleable = [];
     BubbleableMetadata::createFromObject($arg)->applyTo($arg_bubbleable);
     $this->renderer->render($arg_bubbleable);
 }
开发者ID:Greg-Boggs,项目名称:electric-dev,代码行数:28,代码来源:TwigExtension.php


示例19: ajaxView

 /**
  * Loads and renders a view via AJAX.
  *
  * @param \Symfony\Component\HttpFoundation\Request $request
  *   The current request object.
  *
  * @return \Drupal\views\Ajax\ViewAjaxResponse
  *   The view response as ajax response.
  *
  * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  *   Thrown when the view was not found.
  */
 public function ajaxView(Request $request)
 {
     $name = $request->request->get('view_name');
     $display_id = $request->request->get('view_display_id');
     if (isset($name) && isset($display_id)) {
         $args = $request->request->get('view_args');
         $args = isset($args) && $args !== '' ? explode('/', $args) : array();
         // Arguments can be empty, make sure they are passed on as NULL so that
         // argument validation is not triggered.
         $args = array_map(function ($arg) {
             return $arg == '' ? NULL : $arg;
         }, $args);
         $path = $request->request->get('view_path');
         $dom_id = $request->request->get('view_dom_id');
         $dom_id = isset($dom_id) ? preg_replace('/[^a-zA-Z0-9_-]+/', '-', $dom_id) : NULL;
         $pager_element = $request->request->get('pager_element');
         $pager_element = isset($pager_element) ? intval($pager_element) : NULL;
         $response = new ViewAjaxResponse();
         // Remove all of this stuff from the query of the request so it doesn't
         // end up in pagers and tablesort URLs.
         foreach (array('view_name', 'view_display_id', 'view_args', 'view_path', 'view_dom_id', 'pager_element', 'view_base_path', AjaxResponseSubscriber::AJAX_REQUEST_PARAMETER) as $key) {
             $request->query->remove($key);
             $request->request->remove($key);
         }
         // Load the view.
         if (!($entity = $this->storage->load($name))) {
             throw new NotFoundHttpException();
         }
         $view = $this->executableFactory->get($entity);
         if ($view && $view->access($display_id)) {
             $response->setView($view);
             // Fix the current path for paging.
             if (!empty($path)) {
                 $this->currentPath->setPath('/' . $path, $request);
             }
             // Add all POST data, because AJAX is always a post and many things,
             // such as tablesorts, exposed filters and paging assume GET.
             $request_all = $request->request->all();
             $query_all = $request->query->all();
             $request->query->replace($request_all + $query_all);
             // Overwrite the destination.
             // @see the redirect.destination service.
             $origin_destination = $path;
             // Remove some special parameters you never want to have part of the
             // destination query.
             $used_query_parameters = $request->query->all();
             // @todo Remove this parsing once these are removed from the request in
             //   https://www.drupal.org/node/2504709.
             unset($used_query_parameters[FormBuilderInterface::AJAX_FORM_REQUEST], $used_query_parameters[MainContentViewSubscriber::WRAPPER_FORMAT], $used_query_parameters['ajax_page_state']);
             $query = UrlHelper::buildQuery($used_query_parameters);
             if ($query != '') {
                 $origin_destination .= '?' . $query;
             }
             $this->redirectDestination->set($origin_destination);
             // Override the display's pager_element with the one actually used.
             if (isset($pager_element)) {
                 $response->addCommand(new ScrollTopCommand(".js-view-dom-id-{$dom_id}"));
                 $view->displayHandlers->get($display_id)->setOption('pager_element', $pager_element);
             }
             // Reuse the same DOM id so it matches that in drupalSettings.
             $view->dom_id = $dom_id;
             $context = new RenderContext();
             $preview = $this->renderer->executeInRenderContext($context, function () use($view, $display_id, $args) {
                 return $view->preview($display_id, $args);
             });
             if (!$context->isEmpty()) {
                 $bubbleable_metadata = $context->pop();
                 BubbleableMetadata::createFromRenderArray($preview)->merge($bubbleable_metadata)->applyTo($preview);
             }
             $response->addCommand(new ReplaceCommand(".js-view-dom-id-{$dom_id}", $preview));
             return $response;
         } else {
             throw new AccessDeniedHttpException();
         }
     } else {
         throw new NotFoundHttpException();
     }
 }
开发者ID:eigentor,项目名称:tommiblog,代码行数:90,代码来源:ViewAjaxController.php


示例20: preRenderText

 /**
  * Pre-render callback: Renders a processed text element into #markup.
  *
  * Runs all the enabled filters on a pi 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
PHP Render\Element类代码示例发布时间:2022-05-23
下一篇:
PHP Plugin\PluginBase类代码示例发布时间:2022-05-23
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap