Drupal: How to access fields in html.tpl.php

When developing my AMP subtheme for Drupal 7, I wanted to only include the amp-youtube extension if the current page actually contained a YouTube video. The amp-youtube extension javascript can only be included in the HEAD of the HTML document, so in Drupal, your html.tpl.php must know about content which is usually only available at node.tpl.php level. Here is the solution:

In your template.php

function MYTHEME_preprocess_html(&$vars) {
//we need to know if the page contains a YouTube video, so we create the variable below and reference it in html.tpl.php
if ($node = menu_get_object()) {
$vars['youtube_video_id'] = $node->field_youtube_video_id;
}
}

in your html.tpl.php

<?php
//include amp-youtube extention if page contains a YT video
if ($youtube_video_id):
?>
    <script async custom-element="amp-youtube" src="https://cdn.ampproject.org/v0/amp-youtube-0.1.js"></script>
<?php endif;?>

 

Published
Categorized as AMP, Drupal