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 &$page) {
$current_path = \Drupal::service('path.current')->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' => 'meta',
'#attributes' => [
'name' => 'tags',
'data-type' => 'course',
'class' => 'swiftype',
'content' => '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 &$page) {
$node = \Drupal::routeMatch()->getParameter('node');
if ($node instanceof \Drupal\node\NodeInterface) {
if ($node->getType() === 'instance') {
$metatag = [
'#tag' => 'meta',
'#attributes' => [
'name' => 'tags',
'data-type' => 'course',
'class' => 'swiftype',
'content' => '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.
\core\modules\system\templates\html.html.twig
it's core template you should override it in your custom module or theme second thing this isif (preg_match('$^course/', $_SERVER['REQUEST_URI']])) { print_metatag }
php can't be in twig. Did you use metatags module ? – berramou Nov 29 '19 at 20:42