0

I'm creating a custom module. This module displays public custom content without node and views . For this content custom page , I would like to add dynamic meta keyword and meta description .

I have read this excellent answer How do I add a meta tag in <head>...</head> section? and it said we can use

mymodulename_page_attachments(&$page) 

and update variable

$page

But the meta contents are getting in a controller's method. For this raison, I would like to pass the meta contents to mymodulename_page_attachments hook.

How can I call and update $page in my controller module to do this ? Or how can I generate meta in my controller ?

3
  • 1
    Move the logic into a service then use the service in both contexts (controller and hook). You can statically cache the results of the op if it’s expensive. Or maybe try attaching html_head to the render array you return from the controller and see if it bubbles up to the page layer (something tells me it will but I’m not sure)
    – Clive
    Feb 7, 2018 at 9:59
  • tank's I didn't think to this. I will try .
    – Agriesean
    Feb 7, 2018 at 12:29
  • @Clive than'ks . Your message told me what to do and what to learnt . ^^
    – Agriesean
    Feb 8, 2018 at 9:03

2 Answers 2

1

hook_page_attachments() is only needed so you can attach it to any possible route/url. You should be to just add it directly to the response that you re returning, and it should bubble up and be added.

1
  • thank's to your response . I didn't understood realy what was Drupal Service. It's mistake . :-)
    – Agriesean
    Feb 8, 2018 at 9:06
0

Service was the key to my problem .

After i understood Drupal services https://www.drupal.org/docs/8/api/services-and-dependency-injection/services-and-dependency-injection-in-drupal-8

and

http://valuebound.com/resources/blog/how-to-define-your-own-services-drupal-8

It's easy to define dynamic keyword and meta to one page

function mymodulename_page_attachments(array &$page) {
    $currentUrl = Drupal::request()->get(Symfony\Cmf\Component\Routing\RouteObjectInterface::ROUTE_NAME); 
    switch($currentUrl){
        case 'path_url': 
        //call my service 
          $description = array(
                '#tag' => 'meta',
                '#attributes' => array(
                    'property' => 'description',
                    'content' => /* value to my service return */,
                ),
            );

            $page['#attached']['html_head'][] = [$description, 'description'];
        break;

    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.