(easy) Ror : Create helper in view. But how?
I'm discovering R开发者_开发百科ails and I'm sure the way to do what I want is not what I did heure under. can you advice me on the manner to do this properly ??
I would like to create a helper and to use my "flag" variable to see which background I can use.
this is the behaviour I would like : - if I'm in /groups/:id , I want to display the background :id.jpg if it exists - if not, I would like to display a random image which is given by my javascript ImagesAleatoire();
Thanks for helping
<% flag = false
if (params[:id]) and (request.request_uri[1..7] == "groups/")
file = "/images/groups/"+params[:id]+".jpg";
else
file = ""
end
if (File.exists?("public"+file)) %>
<% flag = true %>
<div id="header" style="background : url('<%= file %>') 114px top #2d8872;">
<% else %>
<div id="header" style="background-color : #2d8872;">
<% end %>
<div id="searchzone">
<div id="personnage">
<% unless (flag) %> <script>Images_Aleatoire(); </script> <% end %>
</div>
</div>
...
A helper like this under app/helpers/
:
module FlagHelper
def flag_exists?
flag_file && File.exists?("public"+flag_file)
end
def flag_file
"/images/groups/"+params[:id]+".jpg" if params[:id]
end
end
And in your view:
<% if (flag_exists?) %>
<div id="header" style="background : url('<%= flag_file %>') 114px top #2d8872;">
<% else %>
<div id="header" style="background-color : #2d8872;">
<% end %>
<div id="searchzone">
<div id="personnage">
<% unless (flag_exists?) %>
<script>Images_Aleatoire();</script>
<% end %>
</div>
</div>
you could try this helper function
def group_bg_picture
if (params[:controller] == "groups") && (params[:id])
file = "/images/groups/#{params[:id]}.jpg";
"background:url('#{file}') 114px top #2d8872;" if File.exists? "public"+file
else
""
end
end
and in your view:
<% bg_picture = group_bg_picture %>
<div id="header" style="<%= bg_picture || 'background-color : #2d8872;' %>">
<% unless (bg_picture.present?) %>
<script>Images_Aleatoire(); </script>
<% end %>
精彩评论