2017-01-11 2 views
0

のビューに%selectオプションを表示するには、JSONのパラメータがあります。これはコントローラのsinatraにあります。 newPage.hamlビューでJSONデータでhamlビューに選択オプションを設定する

response = JSON.parse(curl_resp) 
nestedData = response["data"][0] 
    nestedData.each do |c| 
    names = c["attributes"]["names"] 
end 
return haml :newPage, :locals => {:name => example: name in names} 

この%selectオプション::私が持っているsinatraコントローラで

%select{:name => "select names"} 
    %option{:value => "id1"} #{locals[:name]}.[0] 
    %option{:value => "id2"} #{locals[:name]}.[1] 
    %option{:value => "id3"} #{locals[:name]}.[2] 
    %option{:value => "id4"} #{locals[:name]}.[3] 

これは私がcurlから取得するサンプルJSONです:

{"data":[ 
    {"id":"id1","attributes":{"name":"gnu"}}, 
    {"id":"id2","attributes":{"name":"Alice"}}, 
    {"id":"id3","attributes":{"name":"testsubject"}}, 
    {"id":"id4","attributes":{"name":"testissuer"}} 
]} 

答えて

0

# app.rb 

get '/' do 
    # This is obtained from JSON.parse-ing the incoming data. I've used the JSON 
    # value directly 
    @json = { 
    data:[ 
     {id:"id1",attributes:{name:"gnu"}}, 
     {id:"id2",attributes:{name:"Alice"}}, 
     {id:"id3",attributes:{name:"testsubject"}}, 
     {id:"id4",attributes:{name:"testissuer"}} 
    ] 
    } 
    haml :index 
end 

とビューで:

/index.haml 

%select 
    = @json[:data].each do |data_item| 
    %option{ value: data_item[:id] } 
     = data_item[:attributes][:name] 

このように、あなたは、ハードコードする必要はありません要件は、次のようなものを使用することができ、全体のデータセットとディスプレイ上<option>タグを反復することですテンプレート内のオプションタグの数が増えるため、より複雑になります。

関連する問題