Rails - Trouble with setting var and getting value on layout
I'm having a newb moment, trying to find the right (rails) way to set a variable on a show.html.erb and get the value on my layout.
In show.html.erb I am setting a var like so:
<% @meta_title = @content.meta_title %>
In my layout, I want to set that to my <title>
if it is defined and has length, otherwise I want to use a default site setting (loaded from a config.yml).
In /views/layouts/public.html.erb
<%= @meta_title ? @meta_title : APP_CONFIG[:site][:title] %>
I've tried many variations but can't seem to nail the conditions down, things like this:
<%= !@meta_title.blank? ? @meta_title : APP_CONFIG[:site][:title] %>
<%= !@meta_title.nil? || meta_title.length? ? @meta_title : APP_CONFIG[:site][:title] %>
This should be easier for开发者_如何学Go me but I always have difficulty w/ the if, unless
statements. Can you lend a hand? Thanks!
layouts cannot get variables from your show templates and there is no reason to actually do this on the show action since you want it in your layout.
In your application_helper.rb:
def meta_title(title)
if title
title
else
TITLE_CONSTANT
#or even just add the text here such as "My Home Page"
end
end
Then in your layout:
<%= meta_title(@meta_title) %>
This will give you the default of the instance variable if there is one. Don't forget to set your constant in config/initializers/constants.rb
or just use text in the helper.
You can't do that, think the view as a partial of the layout that is render after the layout is render, so when the layour try to access that variable your view is not being processed and so the variable not been saved.
What you have to do is set that variable in the controller. The view should only be used for the render of data, this data should be created within your controller.
If it is not possible to set this variable on the controller then try to use content_for
精彩评论