Home > Software design >  Add condition in a application/ld json type script
Add condition in a application/ld json type script

Time:11-08

I need to write a application/js json type script. It is necessary to have the person scheme, it is a signal that it sends to Google, the search engines being thus able to optimally read the typology of the page and its content. My code 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>

My problem is that if the post.author is null, I have an error Impossible to access an attribute ("firstName") on a null variable. I can not change the author to be required. I don't know how I suppose to put a condition here.

I found that in a ld json application you need to specify if you accept null and I tried this:

  {
        "@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": "[ ]"
            }]
        }
    }

but doesn't work.

Also I tried to put in a variable the value of the author, and use that in the script, something like this:

if ( {{ post.author }}) {
    let author = '{{ post.author.firstName }} {{ post.author.lastName }}';
    let authorurl = {{ user_handler.url(post.author) }};
} else {
    let author = '[]';
    let authorURL = '[]';
}

What I suppose to do?

CodePudding user response:

I resolved it. I added the condition in the twig block like this

 {% 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 %}

and in the script area, I used the variables created.

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