元标记og:用于Facebook分享Rails应用程序的图像

问题描述

我有一个包含文章页面,并且可以从后端为文章设置图像。在表演动作中,我想获取标记og:image,以便与该图像共享Facebook中的文章。 我用以下方式显示图像:

<%= image_tag @article.image_url,:class => "img-fluid" %>

但是当我在url中复制并粘贴网址时,我也无法在facebook帖子中自动获得图片

您有什么建议吗? 预先谢谢你。

解决方法

根据此处的这篇文章,您需要更多的设置。

https://www.lewagon.com/blog/setup-meta-tags-rails

  1. config/meta.yml中创建默认元标记,并将其加载到初始化程序中:
meta_product_name: "Product Name"
meta_title: "Product name - Product tagline"
meta_description: "Relevant description"
meta_image: "cover.png" # should exist in `app/assets/images/`
# config/initializers/default_meta.rb

# Initialize default meta tags.
DEFAULT_META = YAML.load_file(Rails.root.join("config/meta.yml"))

您可以在application.html.erb

中使用它们
<title><%= meta_title %></title>
<meta name="description" content="<%= meta_description %>">

<!-- Facebook Open Graph data -->
<meta property="og:title" content="<%= meta_title %>" />
<meta property="og:type" content="website" />
... 

我将其缩短了,但请参阅文章以获取完整代码。

  1. 对于动态标题或图像,请使用Rails的content_for方法并创建一个辅助方法:
<!-- app/views/any_model/any_view.html.erb -->
<% content_for :meta_image,image_path(@any_model.photo.path) %>

助手将如下所示:

# app/helpers/meta_tags_helper.rb
module MetaTagsHelper
  def meta_image
    meta_image = (content_for?(:meta_image) ? content_for(:meta_image) : DEFAULT_META["meta_image"])
    # little twist to make it work equally with an asset or a url
    meta_image.starts_with?("http") ? meta_image : image_url(meta_image)
  end
end

再次简化,但是您会在源代码中找到完整的代码。