Include a requirement within an application/ld+json formatted script

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?

Answer №1

After tackling the issue, I implemented a condition within the twig block as follows:

 {% if  post.author is empty %}
    {% set author = '[]' %}
    {% set authorUrl = '[]' %}
{% else %}
    {% set author = '{{ post.author.firstName }} {{ post.author.lastName }}'%}
    {% set authorUrl = '{{ user_handler.url(post.author) }}' %}
{% endif %}

Subsequently, I utilized the newly created variables in the script section.

"author": [{
          "@type":  "Person",
          "name": "{{ author }}",
          "url": "{{ authorUrl }}"
       }]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Jquery script that utilizes the Steam WebAPI to return data

I'm encountering an issue with a script I found on github. I added value.appid myself, thinking it was logical, but I believe that data.response.games contains values for all my games. How can I either print or view what is defined? I would like to ...

What is the proper way to utilize the toISOString() function in JavaScript?

My current code uses currentDate.toISOString() to output the date in this format: "2013-01-15T12:08:54.135Z". However, I actually need the date to be formatted like this: "2013-01-15T12:08:54-06:00". The "-06:00" represents the timezone. ...

What is the process for including a task in the current method?

I've been working on building a web app similar to Google Calendar. I have successfully created the necessary objects and methods, but now I need to implement a feature that allows users to add tasks. My current idea is for users to input a task which ...

Struggling to integrate pdfform.js into a React application

Struggling to integrate the pdfform.js library into my React app. I attempted to use the npm package pdfform, but encountered some difficulties. If anyone has any tips or guidance, it would be greatly appreciated. Check out the pdfform.js library on GitH ...

Ways to evaluate negative numbers in JavaScript

I need to validate latitude and longitude values within the range of -180 to 180. If a number falls outside of this range, an error should be displayed. Below is the code I have written for this validation: if((markerPoint[0] && parseInt(markerPoint[0] ...

You can click on the link within the Leaflet Popup to trigger JavaScript functionality

My leaflet map is functioning with GeoJSON polygons and popups attached to each one. These popups display information about the polygon. I want a link inside the popup that, when clicked, triggers a JavaScript function to retrieve and display smaller polyg ...

An error has occurred with the Firefox Addon: the module `path` cannot be located within the resource://gre/modules/commonjs/http.js

Currently developing a Firefox add-on on Windows10 with node v5.8.0 and npm v3.5.3, using Firefox v.45.0 The issue arises from the following line of code: var path = require("path"); The error message reads: Message: Module `http` is not found at resou ...

Get geographical coordinates (latitude and longitude) from a database and pass them to a PHP

I have been working on plotting latitude and longitude data from a MySQL database onto a PHP page. Initially, I was able to display the marker without using JSON with the following code: <? $dbname ='insert mysql database name'; ...

managing nested JSON arrays in JavaScript

I have a straightforward task with handling a simple array that is divided into two parts: a group of vid_ids and a single element named page. Initially, I was iterating through the vid_id array using a for loop. However, upon adding the page element, I en ...

Using jQuery to dynamically add a class to elements that have tab focus

I want to apply a css class to elements that are focused by the tab key, without adding the class when focused by a mouse click. I have managed to achieve this using jQuery with the focusin and focusout events. Here is the code that I currently have: $( ...

Can a virtual host proxy utilize an external IP address?

Currently, I have three node apps running on the same server but with different localhost ports. My goal is to create a router that acts as a proxy for each app and then place this proxy in a virtual host. While I am currently testing this setup on my loca ...

Retrieve checkbox selected value using pug and node.js

How can I retrieve the value of a checked checkbox in order to redirect to (href="/player/edit/:id") or (href="/player/delete/: id"), and obtain the player id for editing or deleting? I have omitted other code details such as app.js which includes the ser ...

How can jQuery Validate show validation messages specific to each field?

I need to validate numerous mandatory fields and display alert messages in a specific format: "Please fill in" followed by the field label. Currently, I am manually implementing this validation method as shown below: $("#myform").validate({ rules: { ...

NPM encountered difficulties in resolving the dependency tree

I seem to be encountering a persistent issue that I cannot resolve on my own. My attempt to update webpack and webpack-cli in a project has been met with repeated errors of this nature: npm install webpack@latest --save-dev npm ERR! code ERESOLVE npm E ...

I'm feeling completely lost trying to understand cors in conjunction with fetch, particularly when an options request is

I am using whatwg fetch in the code snippet below: const headers = new Headers(); //uncommenting this causes the preflight options request to be sent //headers.append('x-something', 'foo'); const response = await fetch(&apos ...

Is there a way to link the id selector with the item's id?

In my app, I have a list of items with buttons that can be liked. To ensure uniqueness, I am utilizing the id selector. My goal is to use the item's id and connect it to the id selector for proper distinction. How can I retrieve the id of each item a ...

Converting JSON date information into a C# DateTime object

I have a WCF service that is returning a custom CLR object called Person. This Person class has properties for FullName and BirthDate defined using DataContract and DataMember attributes. [DataContract] public class Person { [DataMember] public string ...

Increase value continuously when button is pressed down using Material UI

I am looking for a way to continuously increment a value while holding down a button. I have already managed to make it increment on click, but now I want to keep it increasing as long as the button is held down. How can this be achieved using material u ...

Retrieve an item from an array based on the unique ID value of the button that was clicked using

I am working with a phones array that is populated with JSON data: var phones = [ { "age": 0, "id": "motorola-xoom-with-wi-fi", "imageUrl": "img/phones/motorola-xoom-w ...

Encountering an error with an undefined callback argument within an asynchronous function

I encountered an issue while working with the viewCart function. I have implemented it in the base controller and am calling it from the home controller. However, I am facing an error where the callback argument in home.js is showing up as 'undefined& ...