Drupal 8,对服务器的 http 请求并附加到站点

Drupal 8, http request to server and append to the site

我有一个 Drupal 8 站点,我需要向另一台服务器发出 http 请求(用于内容)并将其附加到页脚中。由于 SEO 问题,我无法在加载 DOM 后执行此操作。

我熟悉 WordPress,使用 WP 很容易做到。但是,我对如何使用 .twig、Drupal 8 执行此操作感到困惑。任何建议都很好。谢谢。

如果您希望内容在发送到浏览器时成为 DOM 的一部分,这不是您希望在 Twig 中执行的操作,您应该在此过程中更早地加载内容。

您可以 create a module that defines custom block 并将该块放置在主题的正确区域。

块插件 class 要求您编写一个 build() 方法,该方法 return 为您的块提供渲染数组。在 build() 中,您可以做任何您需要的事情来获取内容,包括使用 Symfony 的 Guzzle 客户端发出 HTTP 请求:

public function build() {
  $url = 'https://www.example.com/remote/service';
  $client = \Drupal::httpClient();
  $request = $client->createRequest('GET', $url);
  // Do whatever's needed to extract the data you need from the request...
  $build = ['my_remote_block' => [
      '#theme' => 'my_custom_theme_function',
      '#attributes' => [
         //An array of variables to pass to the theme
      ],
      '#cache' => [
        //Some appropriate cache settings
      ],
    ],
  ];

如果您从您的请求中得到 HTML 返回,您可以跳过自定义主题功能和 return 一个带有 '#type' => 'markup' 的数组,然后是一个标记字段。此示例的其余部分假设您取回数据并希望自己呈现它。

在模块的 .module 文件中,您可以定义自定义主题功能(因此您可以使用自己设计的 twig 文件)。

function my_module_theme($existing, $type, $theme, $path) {
  return [
    'my_custom_theme_function' => [
      'variables'=> [ 
        // defaults for variables used in this block.
      ],
    ],
  ];
}

最后你可以创建一个 twig 文件 named my-custom-theme-function.html.twig 来渲染输出。

通常这些类型的设置非常慢(因为浏览器的请求然后触发另一个 HTTP 请求 + 处理时间)所以你应该考虑尽可能缓存块或使用像 BigPipe 这样的技术(根据您的问题,这可能不是您的选择,但似乎值得指出)。