I have a task to create an application using a script in the js+json format. It is crucial to include the person schema, which signals to Google and other search engines how to effectively interpret the structure of the page and its content. My current code snippet looks like this.
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "Article",
"headline": "{{ article.title }}",
"image": "{{ article_handler.coverUrl(post, 'm') }}",
"datePublished": "{{ article.publishedAt|date('Y-m-d h:i:s') }}",
"dateModified": "{{ article.updatedAt|date('Y-m-d h:i:s') }}",
"author": [{
"@type": "Person",
"name": "{{ post.author.firstName }} {{ post.author.lastName }}"
}]
}
</script>
The issue I face is when post.author is null, resulting in an error message stating "Impossible to access an attribute ('firstName') on a null variable." As I cannot make the author field required, I am unsure how to handle this situation within the script.
I learned that in an ld+json application, specifying if null values are accepted is necessary. I attempted the following approach:
{
"@context": "https://schema.org",
"@type": "Article",
"headline": "{{ article.title }}",
"image": "{{ article_handler.coverUrl(post, 'm') }}",
"datePublished": "{{ artcile.publishedAt|date('Y-m-d h:i:s') }}",
"dateModified": "{{ article.updatedAt|date('Y-m-d h:i:s') }}",
"if": {
"{{ post.author }}": {
"type": ["string", "null"]
}
},
"then": {
"author": [{
"@type": "Person",
"name": "{{ post.author.firstName }} {{ post.author.lastName }}"
}]
},
"else": {
"author": [{
"@type": "Person",
"name": "[ ]"
}]
}
}
However, this solution was unsuccessful.
I also attempted to store the author value in a variable and use it in the script, as shown below:
if ( {{ post.author }}) {
let author = '{{ post.author.firstName }} {{ post.author.lastName }}';
let authorurl = {{ user_handler.url(post.author) }};
} else {
let author = '[]';
let authorURL = '[]';
}
What would be the appropriate approach to address this issue?