2011-07-05 6 views
0

私はRailsを発見しています。私が望むことをやり遂げる方法は、私が頑張ったものではないと確信しています。 これを正しく行う方法についてアドバイスをいただけますか?(簡単)Ror:ヘルパーをビューで作成します。しかしどうですか?

私はヘルパーを作成し、 "flag"変数を使用して、どのバックグラウンドを使用できるかを確認したいと思います。 - 私が/ groups /:idにいる場合は、背景を表示したい:id.jpgが存在する場合は - そうでない場合、ランダムを表示したいと思います。私のjavascript ImagesAleatoire()によって与えられた画像; app/helpers/

<% 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> 
... 

答えて

0

にこのようなヘルパーを支援するための

ありがとう:

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 

そして、あなたのビューで:

<% 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> 
0

あなたはこのヘルパー関数を試みることができる

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 

と表示されます。

<% bg_picture = group_bg_picture %> 
<div id="header" style="<%= bg_picture || 'background-color : #2d8872;' %>"> 
<% unless (bg_picture.present?) %> 
    <script>Images_Aleatoire(); </script> 
<% end %> 
関連する問題