Home > Net >  Rails 6 Creating IF statement for conditional meta_tag based on DB value
Rails 6 Creating IF statement for conditional meta_tag based on DB value

Time:11-18

I have looked at multiple pages, but my brain cannot bridge the gap to how this problem should look answered.

Problem: I need very specific DB generated show pages to have <meta name="robots" content="noindex">. I know this will require an IF statement somewhere. So it boils down to I need specific DB driven pages in my people index to not be indexed by search engines as their pages are really not supposed to exist. (If a @person.position == "hide" they need to not exist to a search engine)

Setup: My app is setup with a layout/application page that contains all html, header, footer, meta data, and a yield call for all of the data for each page shown in the browser.

I am not sure where the if statement will go. Will I need to add a call to the controller? The more I look at this it seems like a super sloppy approach.

CodePudding user response:

You can use the captures helper to create dynamic chunks in your layout that can be filled in by the view.

<html>
  <head> 
    # ...
    <%= yield :meta %>
  </head>

  # ...
# app/views/people/show.html.erb
<%= content_for :meta do %>
  <meta name="robots" content="noindex">
<% end if @person.hide_from_robots? %>
....
class Person
  # Encapsulate the logic in the model
  def hide_from_robots?
    position == "hide"
  end
end

Another way to do this is by sending the X-Robots-Tag header instead of using a meta tag:

class PeopleController < ApplicationController
  def show
    @person = Person.find(params[:id])
    noindex_nofollow if @person.hide_from_robots?
  end

  private

  def noindex_nofollow
    response.headers['X-Robots-Tag'] = 'noindex, nofollow' 
  end
end

CodePudding user response:

If you're using ERB to render your HTML, you can do the if statement directly on the HTML file.

<% if @person.position == "hide" %>
  <meta name="robots" content="noindex">
<% end %>
  • Related