简体   繁体   中英

Looping over JSON-ld schema with JS foreach in GTM

I'm setting up a schema for a restaurant page using JSON-ld in Google Tag Manager. The menu sections update regularly, so would like to loop through this section in the schema using dynamic variable using a data layer variable or javascript variable.

<script type="application/ld+json">
(function(){


    var data = {
      "@context":"http://schema.org",
      "@type":"Restaurant",
      "url":"https://www.example.com/",
      "name":"Example",
      "hasMenu":{
         "@type":"Menu",
         "name":"Menu",
         "description":{{Menu Description}},
         "hasMenuSection":[{                                 //loop through from here
               "@type":"MenuSection",
               "name":{{Menu Section Name}},
               "description":{{Menu Section Description}},
               "image":{{Menu Section Image}},
         }]
      }
   }}
    var script = document.createElement('script');
    script.type = 'application/ld+json';
    script.innerHTML = JSON.stringify( data );
    document.getElementsByTagName('head')[0].appendChild(script);
})(document);
</script>

My variables are custom JS, however, this also doesn't seem to select the correct elements. eg {{Menu Section Name}}

function () {return  document.querySelectorAll('#menu-section-name');}

I was looking at this question How to use Google Tag Manager with Multiple Schema Product reviews using JSON-LD and Variables But the answer doesn't quite follow through with the full implementation. There's also an option here looking at looping through the json data https://nystudio107.com/blog/annotated-json-ld-structured-data-examples but this is in twig and doesn't look at implementation in GTM.

Maybe something like this:

         "hasMenuSection":
            [...document.querySelectorAll('#menu-section-name')]
              .map( section => {
                "@type": "MenuSection",
                "name": section.querySelectorAll('.section-name').textContent,
                "description": section.querySelectorAll('.section-description').textContent,
                "image": section.querySelectorAll('.section-image').src,
              })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM