JSON_LD Code in Layout-File

To provide structured data for Google, I followed Schema-Markup für Rezepte | Google Search Central  |  Documentation  |  Google for Developers and inserted some code into the head area in the layout-file to provide the data for Google:

 <head>
<?= $this->Html->charset() ?>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>
        <?= $cakeDescription ?>
        <?php
          //  if (isset($pageTitle) AND !empty($pageTitle)) {
           //     echo ' - '.$pageTitle;
           // }
        ?>
        <?php
            //echo $this->fetch('title');
        ?>
    </title>
    
    <?= $this->Html->meta('icon','favicon.svg',['type' => 'image/svg+xml'])?>
    <?= $this->Html->css(['stylesheet']) ?>
    <?php $this->Html->script('searchRecipes', ['block' => 'scriptBottom']); ?>

   
    <?= $this->fetch('meta') ?>
    <?= $this->fetch('css') ?>
    <?= $this->fetch('script') ?>

    <!-- **************************************-->
    <!-- Google Part-->
    <?php
        $controller=$this->request->getParam('controller');
        $action=$this->request->getParam('action');
        if (($controller=='Recipes') AND ($action=='showrecipe') AND (isset($recipe)))
        {
            //debug($recipe);
            foreach ($recipe->ingredients_recipes as $ingredient) {
                $data='';
                if ($ingredient->hasValue('amount')) {
                    $amount = $ingredient->amount->name;
                    $data .= $amount.' ';
                } 
                if ($ingredient->hasValue('measurement')) {
                    $measurement = $ingredient->measurement->name;
                    $data .= $measurement .' ';
                } 
                if ($ingredient->hasValue('ingredient')) {
                    $ingredientname =$ingredient->ingredient->name;
                    $data .= $ingredientname;
                } 
                $ingredients[] = $data;
            }
            foreach ($recipe->preparationsteps AS $preparationstep) {
                $data = array(
                    '@type' => 'HowToStep',
                    'text'=>$preparationstep->name
                );
                $preparationsteps[] = $data;
            }
            $json=array(
                "@context"=> "https://schema.org/",
                "@type" => "Recipe",
                "name" => $recipe->name ,
              );
            if ($recipe->hasValue('recipepictures')) {
                $json["image"] = RecipePictures.$recipe->recipepictures[0]->name;
            }
            if ($recipe->hasValue('description')) {
                $json["description"] = $recipe->description;
            }
            if ($recipe->hasValue('preparationtime')) {
                $json["prepTime"] = $recipe->preparationtime;
            }
            if ($recipe->hasValue('cookingtime')) {
                $json["cookTime"] = $recipe->cookingtime;
            }
            if ($recipe->hasValue('servings')) {
                $json["recipeYield"] = $recipe->servings;
            }
            if ($recipe->hasValue('occasions')) {
                $data='';
                foreach($recipe->occasions AS $occasion) {
                    $data.= $occasion->name.',';
                }
                $json["keywords"] = $data;
            }
            $cuisines = null;
            if ($recipe->hasValue('worldcuisine')) {
                $cuisines.=$recipe->worldcuisine->name.',';
            }
            if ($recipe->hasValue('nationalcuisine')) {
                $cuisines.=$recipe->nationalcuisine->name.',';
            }
            if ($recipe->hasValue('regionalcuisine')) {
                $cuisines.=$recipe->regionalcuisine->name.',';
            }
            if (isset($cuisines)) {
                $json["recipeCuisine"] = $cuisines;
            }
            

            if ($recipe->hasValue('meals')) {
                $data='';
                foreach($recipe->meals AS $meal) {
                    $data.= $meal->name.',';
                }
                $json["recipeCategory"] = $data;
            }

            $json["author"]= ["@type"=>"Person","name"=>$recipe->user->name];
            $json["datePublished"] = $recipe->created->i18nFormat("dd. MMMM yyyy");
            if (isset($ingredients)) {
                $json["recipeIngredient"] = $ingredients;
            }
            if (isset($preparationsteps)) {
                $json["recipeInstructions"] = $preparationsteps;
            }
            
            echo '<script type="application/ld+json">';
            echo json_encode($json,  JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
            echo "</script>";
        }
    ?>
    <!-- End of Google Part-->
    
</head>

For me it seems to be overkill, because the whole code-block is only needed, if the the action “showrecipe” is called.
Is there a way to put this code into a separate file and call it from the method “showrecipe” in controller “recipes”?

In your layout, put <?= $this->fetch('googlepart') ?>, and then in the template for anything that needs to have Google code you would have

$this->start('googlepart');
// all your code to generate that block
$this->end();

Thank you very much for your help!