我需要撰寫一個 application/js json 型別的腳本。有必要有個人計劃,這是它發送給谷歌的信號,搜索引擎因此能夠最佳地讀取頁面的型別及其內容。我的代碼看起來像這樣。
<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>
我的問題是,如果post.author為 null,我將出現錯誤Impossible to access an attribute ("firstName") on a null variable。我無法更改所需的作者。我不知道我應該如何在這里提出條件。
我發現在 ld json 應用程式中你需要指定是否接受 null 我試過這個:
{
"@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": "[ ]"
}]
}
}
但不起作用。
我還嘗試將作者的值放入變數中,并在腳本中使用它,如下所示:
if ( {{ post.author }}) {
let author = '{{ post.author.firstName }} {{ post.author.lastName }}';
let authorurl = {{ user_handler.url(post.author) }};
} else {
let author = '[]';
let authorURL = '[]';
}
我該怎么辦?
uj5u.com熱心網友回復:
我解決了。我像這樣在樹枝塊中添加了條件
{% 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 %}
在腳本區域,我使用了創建的變數。
"author": [{
"@type": "Person",
"name": "{{ author }}",
"url": "{{ authorUrl }}"
}]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/533881.html
上一篇:如何使用doctrine/postgresql[symfony]獲取隨機元素
下一篇:將字母?轉換為open
