Dynamically-Generated JSON-LD for BreadcrumbList

Hi,

Wondering if anyone has a HubL snippet they use for dynamically generating JSON-LD for breadcrumbs. I originally thought `content.topic_list` would contain every segment in the blog post’s URL, but I was incorrect. Given the following URL:

https://www.mysite.com/segment1/segment2/page-name

How would go about dynamically generating a breadcrumb JSON as below?

{
 "@type": "BreadcrumbList",
 "itemListElement": [
 {
 "@type": "ListItem",
 "position": 1,
 "name": "Home",
 "item": "https://www.mysite.com"
 },
 {
 "@type": "ListItem",
 "position": 2,
 "name": "Segment1",
 "item": "https://www.mysite.com/segment1"
 },
 {
 "@type": "ListItem",
 "position": 3,
 "name": "Segment2",
 "item": "https://www.mysite.com/segment1/segment2"
 },
 {
 "@type": "ListItem",
 "position": 4,
 "name": "Page Name",
 "item": "https://www.mysite.com/segment1/segment2/page-name"
 }
 ]
 }

Hi, @DInc :waving_hand: Thanks for your question. I’d like to invite some of our community experts to the conversation — hey @albertsg @alyssamwilie @Anton @Teun do you have any experience creating this dynamically in the manner @DInc is describing?

I found this blog post from @AJLaPorte that I’ll leave for other folks who may come across your post when searching.

Thank you very much for taking a look! — Jaycee

Thanks for your reply @Jaycee_Lewis. After many attempts - and failures - in generating a dynamic list of absolute URLs from a URL with multiple segments, I decided to add a repeater Bradcrumbs schema field as a module and let the editor speficy them on their own. Though, if there was an object provided to keep track of the various ‘crumbs’ leading to every page/blog post, I imagine we could iterate through that to generate a viable BradcrumbList schema.

Hi @DInc,

Assuming all the path URLs are pages, you can split the path and construct as list items:

For example:

{% set url_segments = request.path.split('/') %}
{
 "@type": "BreadcrumbList",
 "itemListElement": [
 {% for segment, i in url_segments %}
 {
 "@type": "ListItem",
 "position": {{ i+1 }},
 "name": "{{ segment|capitalize }}",
 "item": "{{ request.base_path }}/{{ segment }}"
 }
 {% if not loop.last %},{% endif %}
 {% endfor %}
 ]
}

Let me know if you need to integrate the post’s topic into the breadcrumb.

This wouldn’t work because each segment’s absolute url would need to contain the previous segment as part of its url, if it exists. Using your example, I would end up with `https://www.mysite.com/page-name` as the last segment’s absolute URL, which would be incorrect.