带有 slim-rails 的元标记

Meta tags with slim-rails

我目前正在进行网站扫描,并试图为已在生产中的应用程序改进元表示。具体来说,标签似乎存在于 _head.html.slim 文件中。

元标记当前在应用中的表示方式示例:

    - if content_for?(:description)
meta name="description" content=content_for(:description)

我想将其替换为:

    <meta property="og:description" content="DESCRIPTION OF SITE HERE"/>

我在正确的轨道上吗?我犹豫是否要完全擦除“if content_for?(:description) 位。

我以前没有使用过 slim-rails,所以被抛弃了。我已经浏览了一些关于 slim gem 的文档,但它定义元标记实现的方式与我目前在 _head.html.slim 文件中看到的方式完全不同。

如有任何建议,我们将不胜感激。

content_for actually part of Rails and has very little to do with Slim. yield and content_for 允许您在布局中分配 "blocks" 可以由视图动态填充的内容。

这是动态分配页面标题的普通 ERB 示例:

# app/views/layouts/application.html.erb
<title>MyApp | <%= content_for?(:title) ? yield(:title) : "Foo" %>

然后在您的视图中,您可以提供以下内容的内容:

# app/views/products.html.erb
<%- contents_for(:title, "Products" ) -%>

最终结果是,当您访问 /products 时,页面标题将显示为 MyApp | Products

对于您的示例,您可以简单地提供视图中描述的内容。

# app/views/user/show.slim
- content_for(:description, "#{ @user.name } on MyApp")
# or we use provide to tell the layout to stop looking for more contents.
- provide(:description, "#{ @user.name } on MyApp")

并将其设置为在未提供内容的情况下显示默认值。

= meta name="description" content= content_for?(:description) ? yield(:description) : "The awesomest app on the interwebs."

要清理它,您可能需要使用辅助方法。

module ApplicationHelper
  # ...
  def og_description(default)
    # note that we use content_for and not yield since we want
    # the value - not to yield (print) to the buffer.
    disc = content_for?(:description) ? content_for(:description) : default 
    tag(:meta, {
      property: "og:description",
      content: disc
    })
  end
end

这会让你做:

= og_description("The awesomest app on the interwebs.")