代码之家  ›  专栏  ›  技术社区  ›  baruchiro

如何在twitter上使用封面图片作为卡片图片

  •  0
  • baruchiro  · 技术社区  · 5 年前

    我想用Gridsome metaInfo 创建一个 Twitter Card 封面图片 但卡片上没有显示图像。

    <template>
      <Layout>
      ...
        <g-image ref="coverImage" alt="Cover image" v-if="$page.post.cover_image" :src="$page.post.cover_image" />
      ...
      </Layout>
    </template>
    
    <script>
    export default {
      metaInfo () {
        return {
          title: this.$page.post.title,
          meta: [{
            property: 'og:image',
            content: this.$refs.coverImage? this.$refs.coverImage.src : (this.$page.meta.siteUrl + '/logo/LOGO.png')
          }]
        }
      }
    }
    </script>
    
    <page-query>
    query Post ($id: ID!) {
      post: post (id: $id) {
        title
        path
        cover_image (width: 860, blur: 10)
      },
      meta: metadata {
        siteUrl
      },
    }
    </page-query>
    

    自从 g-image 知道如何解析图像路径我必须使用它才能将图像路径放入 meta 标签。


    编辑 -这个问题是为了记录我的知识,我知道答案,我希望这个问题本身是好的

    1 回复  |  直到 5 年前
        1
  •  1
  •   marc_s MisterSmith    5 年前

    得到 Twitter Card 工作需要几个步骤。

    获取真实图像路径

    你说得对,当你质疑 GraphQL 对于图像,您得到的是一个对象,而不是图像路径。但要获得图像路径,只需访问 src 对象中的属性:

    metaInfo () {
      return {
        title: this.$page.post.title,
        meta: [{
          property: 'og:image',
          content: this.$page.post.cover_image?.src || '/logo/LOGO.png'
        }]
      }
    }
    

    获得正确的图像大小

    此卡的图像支持 纵横比为2:1 最小尺寸为300x157或最大尺寸为4096x4096像素
    Twitter Docs (搜索 twitter:image )

    在网上,你可以找到推荐的尺寸是 1200x630 ,请参阅 Open Graph Docs 例如

    当然,最好确保使用的图像尺寸正确,但即使图像不是脚,也可以通过 GraphQL ,并在需要时裁剪您的图像:

    <page-query>
    query Post ($id: ID!) {
      post: post (id: $id) {
        ...
        cover_image (width: 1200, height: 630)
      },
    }
    </page-query>
    

    完整图像路径

    啁啾 需要一个 完整路径 为了你的形象( 脸谱网 ,例如,接受相对于主机的路径),因此需要加入 siteUrl 到图像路径:

    meta: [{
      name: 'twitter:image',
      content: this.$page.meta.siteUrl + (this.$page.post.cover_image?.src || '/logo/LOGO.png')
    }]
    

    杂项和测试

    当然,你需要定义另一个 meta 标签,请注意 啁啾 标签应该与 name content ,但是 开放图 标签应该与 property 所容纳之物 :

    <!-- For Open Graph -->
    <meta property="og:image" content="path/to/image.png">
    
    <!-- For Twitter -->
    <meta name="twitter:image" content="path/to/image.png">
    

    然后,使用这些工具验证页面,并查看它们的警告:

    此外,你可以使用 Localhost Open Graph Checker 扩展以测试您的本地网站。

    推荐文章