使用 JSON 数据在 haml 视图中填充 select 选项
Populate select options in a haml view with JSON data
如何使用 sinatra
控制器中的 JSON
参数填充 haml
视图中的 %select
选项。
在 sinatra
控制器中我有:
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}
这是 newPage.haml
视图中的 %select
选项:
%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]
这是一个示例 JSON
我从 curl
:
{"data":[
{"id":"id1","attributes":{"name":"gnu"}},
{"id":"id2","attributes":{"name":"Alice"}},
{"id":"id3","attributes":{"name":"testsubject"}},
{"id":"id4","attributes":{"name":"testissuer"}}
]}
如果您的要求是遍历整个数据集并显示 <option>
标签,您可以使用如下内容:
# 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]
这样,您就不必 hard-code 模板中选项标签的数量,否则会使它变得更复杂。
如何使用 sinatra
控制器中的 JSON
参数填充 haml
视图中的 %select
选项。
在 sinatra
控制器中我有:
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}
这是 newPage.haml
视图中的 %select
选项:
%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]
这是一个示例 JSON
我从 curl
:
{"data":[
{"id":"id1","attributes":{"name":"gnu"}},
{"id":"id2","attributes":{"name":"Alice"}},
{"id":"id3","attributes":{"name":"testsubject"}},
{"id":"id4","attributes":{"name":"testissuer"}}
]}
如果您的要求是遍历整个数据集并显示 <option>
标签,您可以使用如下内容:
# 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]
这样,您就不必 hard-code 模板中选项标签的数量,否则会使它变得更复杂。