Rails - How to determine if content_for content has been provided?

I want to determine if content was provided for the content_for tag in my template, and if it does not return to the default value:

<title> <% if content_is_provided -%> <%= yield :title -%> <% else -%> 404 - Page Unknown <% end -%> </title> 

Any easy way to detect this? I tried <% if :title -%> , but it did little. thanks.

+4
source share
5 answers

You can arrange the code further:

 def content_exists?(name) return instance_variable_get("@content_for_#{name}") end 
+3
source

Try the following:

 <title> <%= yield :title || "404 - Page Unknown" -%> </title> 
+2
source

In the old version of Rails 2.1.1

 <%= (yield :title) || default_title %> 

works for me.

+2
source

After digging in the text content_for a bit, I found a working solution by creating a helper method:

 def content_exists?(name) return true if instance_variable_get("@content_for_#{name}") return false # I like to be explicit :) end 

and in view:

 <% if content_exists?(:title)-%> <%= yield :title %> <% else -%> 404 - Page Unknown <% end -%> 

This seems to work now (Rails 2.3.5).

+1
source

Another way

'common / top_status')%>
+1
source

Source: https://habr.com/ru/post/1307921/


All Articles