如何在application/ld+json脚本中处理post.author为空的报错问题?
方案一:模板内添加条件判断(适配Twig类模板引擎)
通过模板的条件语句,仅当post.author存在时才渲染author字段,避免访问null变量的属性:
<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') }}" {% if post.author is not null %}, "author": [{ "@type": "Person", "name": "{{ post.author.firstName }} {{ post.author.lastName }}" }] {% endif %} } </script>
注意:要保证JSON语法正确,author字段前的逗号仅在条件成立时添加,避免出现 trailing comma 错误。
方案二:后端提前处理变量
在后端代码中统一处理作者信息,当post.author为null时设置默认值,模板直接使用处理后的变量即可:
后端示例(PHP)
// 生成作者名称变量 $authorName = $post->author ? ($post->author->firstName . ' ' . $post->author->lastName) : '匿名'; // 或者给post.author赋值默认对象 if (empty($post->author)) { $post->author = (object)[ 'firstName' => '匿名', 'lastName' => '' ]; }
模板代码
<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": "{{ authorName }}" }] } </script>
方案三:使用模板过滤器简化判断
利用模板的条件表达式和默认过滤器,一次性处理null情况(以Twig为例):
<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 ? (post.author.firstName ~ ' ' ~ post.author.lastName) : '匿名' }}" }] } </script>
补充说明
根据Schema.org规范,Article类型的author字段并非必填项。如果没有作者信息,完全省略author字段也是符合要求的,不会影响搜索引擎对页面类型的识别。
内容的提问来源于stack exchange,提问作者Ana Maria A.
相关产品推荐
相关产品推荐

