Injecting metadata into all nodes within one folder For my school I need to add metadata into the  tag of every node/page within the folder /course/

The metadata is the same for every page in this folder:

&lt;meta class="swiftype" name="tags" data-type="string" content="course" /&gt;


This will allow me to use weighting for all our course pages in the Swiftype search app.

I've narrowed it down to the html.html.twig file in \core\modules\system\templates - where I believe I need to be adding something along the lines of:

if (preg_match('$^course/', $_SERVER['REQUEST_URI']])) { print_metatag }


But I won't be wanting to use print_metatag. Instead I should be using the fixed metadata referenced above.

Can anyone help me figure out what I need to use, and where, to apply this metadata to all those /course/ nodes/pages.

Many thanks!
You won't be able to use PHP like that in Twig, but your logic isn't far off. One of the reasons Drupal 8 switched to using Twig was to avoid having potentially unsafe PHP in template files – this sort of thing generally belongs in a module rather than in a template, especially as it's not related to the presentation of content.

Drupal doesn't have a concept of folders, but we can look at the path of the content (e.g. /courses/drupal-development or /contact-us or /news/2018/cool-thing-that-happened) and work out if it's 'under' courses or not that way.

Something like this should work, but is untested:

/**
 * Implements hook_page_attachments().
 */
function YOUR_MODULE_NAME_page_attachments(array &amp;$page) {
  $current_path = \Drupal::service('path.current')-&gt;getPath();
  $exploded_path = explode('/', $current_path);

  // Add Swiftype metatag, see https://swiftype.com/documentation/site-search/crawler-configuration/meta-tags.
  if ($exploded_path[1] === 'courses') {
    $metatag = [
      '#tag' =&gt; 'meta',
      '#attributes' =&gt; [
        'name' =&gt; 'tags',
        'data-type' =&gt; 'course',
        'class' =&gt; 'swiftype',
        'content' =&gt; 'course',
      ],
    ];

    $page['#attached']['html_head'][] = [$metatag, 'swiftype_course'];
  }
}


Or to do it by content type:

/**
 * Implements hook_page_attachments().
 */
function YOUR_MODULE_NAME_page_attachments(array &amp;$page) {
  $node = \Drupal::routeMatch()-&gt;getParameter('node');

  if ($node instanceof \Drupal\node\NodeInterface) {
    if ($node-&gt;getType() === 'instance') {
      $metatag = [
        '#tag' =&gt; 'meta',
        '#attributes' =&gt; [
          'name' =&gt; 'tags',
          'data-type' =&gt; 'course',
          'class' =&gt; 'swiftype',
          'content' =&gt; 'course',
        ],
      ];

      $page['#attached']['html_head'][] = [$metatag, 'swiftype_course'];
    }
  }
}


If you need help setting up a module then take a look at https://befused.com/drupal/first-drupal8-module - but you can stop once you've created a your_module_name.module file – this is the file that the code above will go into.