Search code examples
razorumbracoschema.orgstructured-data

Can I Use Razor Rendered Content in Schema Markup?


I have nearly 1000 articles on my website which is built in Umbraco that I would like to implement with Article Schema markup.

The trouble I have is that most of the content is dynamically generated by razors (e.g. @Umbraco.Field("Title") ). I have tried to put these razors in the relevant code for my markup but Google's Structured Data Testing Tool is showing errors for all of them.

Will this work once live? Or is there a workaround to markup multiple articles on a site to pull the data from other areas on the page?

Thanks for any advice.


Solution

  • Yes, you should be able to do this. I'm assuming the issue you're having is that you're trying to use JSON-LD - this adds complication because it uses the @ symbol which Razor syntax also relies on. In Razor you can escape it with @@. Here's an example on how I've gotten this to work (This isn't Umbraco specific, but it is still standard Razor):

    <script type="application/ld+json">
    {
        "@@context": "http://schema.org",
        "@@type": "article",
        "@@id": "@newsItem.DefaultUrl",
        "mainEntityOfPage": {
            "@@type": "WebPage",
            "@@id": "@newsItem.DefaultUrl"
        },
        "headline": "@newsFields.Title",
        "datePublished": "@newsItem.GetDateTime("PublicationDate", "MMM d, yyyy, HH:mm tt")",
        "dateModified": "@newsItem.GetDateTime("LastModified", "MMM d, yyyy, HH:mm tt")",
        "author": {
            "@@type": "Person",
            "name": "@newsItem.Author"
        }
    }
    </script>
    

    JSON-LD is valid anywhere in the body so you don't have to worry about injecting anything into the head. For me the above rendered standard JSON-LD code and passed in the structured data testing tool. This is a basic example. It can get a little tricky depending on the field but I haven't run into any walls yet.

    Of course another viable option (at least as of this writing) is to use RDFa on your HTML instead, this isn't the ideal approach but definitely can be more flexible.