[英]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.我正在 Google 跟踪代码管理器中使用 JSON-ld 为餐厅页面设置架构。 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.菜单部分定期更新,因此希望使用数据层变量或 javascript 变量使用动态变量在模式中循环浏览此部分。
<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.我的变量是自定义 JS,但是,这似乎也不是 select 正确的元素。 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.我在看这个问题How to use Google Tag Manager with Multiple Schema Product review using JSON-LD and Variables但答案并没有完全贯彻到底。 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. 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,
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.