Score:0

Override the page title with a value from an API response

gt flag

I built a custom Drupal module. The module fetches data from a 3rd-party API and builds a block. I need to use a value from the API response to override the title (and head_title) of the page that the block is placed on.

I tried saving the value to the node in the Block controller:

$node = $this->getContextValue('node');
$node->page_title_override = $apiValue;

And then using that from hook_preprocess_html().

function myModule_preprocess_html(&$variables) {
  $pageTitleOverride = $node->page_title_override;
  $variables['head_title']['title'] = $pageTitleOverride;
}

It appears that the preprocess hook executes before the block controller, so $pageTitleOverride is empty.

Do you have any idea on a better approach?

ru flag
Outsource the API fetching into a custom [service class](https://www.drupal.org/docs/drupal-apis/services-and-dependency-injection/structure-of-a-service-file), and then both block and preprocess function should retrieve their data from that service. Drush has a generate command to create the boilerplate code required for a service class.
mfairhurst avatar
gt flag
@Hudri that works, thank you!
Score:0
cn flag

You are saving the value to the node in the Block controller only temporary, but blocks are not necessarily rendered in the same request. The block could have been cached a long time ago before the page is built or, if the block is not cacheable, it can be cached in the page as a placeholder so that the preprocess hook runs in a later request.

So what you can do depends on how cacheable the block and the title are. The module metatag provides more tools to set the page title dynamically, either through attached html_head metadata or tokens.

I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.