Apr 25, 2019 in Drupal 8

In some cases you would really want to add a snippet somewhere inside your code, inside script tags. This is how you do it: Let's say you want the snippet inside a controller. Create a custom module and add a file named google_snippet.routing.yml with this content:

google_snippet.page:
  path: '/my-custom-path'
  defaults:
    _title: 'Here is my snippet'
    _controller: '\Drupal\google_snippet\Controller\snippetPage::render'
  requirements:
    _permission: 'access content'

Also add a file google_snippet.module file to make the controller aware of a template file:

function google_snippet_theme($existing, $type, $theme, $path) {
  return [
    'google_snippet' => [
      'variables' => [
        'snippet' => NULL
      ],
    ],
  ];
}

Create a file in src/Controller/ named snippetPage.php.

namespace Drupal\google_snippet\Controller;
use Drupal\Core\Controller\ControllerBase;

class snippetPage extends ControllerBase {
  public static function render() {
    return [
      '#theme' => 'google_snippet',
      '#snippet' => '
         <script>
          INSERT YOUR SNIPPET HERE
        </script>
      ',
    ];
  }
}

Then, inside a templates folder of your module a file named google-snippet.html.twig with the following content:

{{ snippet|raw }}