What's the quickest and most elegant way to mark currently selected option value in the form in HAML?
在HAML中以表格形式标记当前所选期权值的最快捷,最优雅的方法是什么?
%form{:action => '', :method => 'get'}
%select{:name => 'param_name'}
%option{:value => 'A'} A data
%option{:value => 'B'} B data
One way:
单程:
- if params[:param_name] == "A"
%option{:value => 'A', :selected => 'selected'} A data
- else
%option{:value => 'A'} A data
but this is inappropriate when the select
box will has many option fields...
但是当选择框有很多选项字段时,这是不合适的...
2 个解决方案
#1
16
Something like this will work (using the older "hashrocket syntax" with the operator =>
)
像这样的东西将起作用(使用较旧的“hashrocket语法”与operator =>)
%select
%option{:value => "a", :selected => params[:x] == "a"}= "a"
%option{:value => "b", :selected => params[:x] == "b"}= "b"
Or, in newer Ruby versions (1.9 and greater):
或者,在较新的Ruby版本(1.9及更高版本)中:
%select
%option{value: "a", selected: params[:x] == "a"}= "a"
%option{value: "b", selected: params[:x] == "b"}= "b"
#2
13
You should unleash the power of rails helpers.
你应该释放铁路助手的力量。
对于选择标签:
= select_tag :param_name, options_for_select([['A data', 'A'], ['B data', 'B']], params[:param_name])
Also, instead of raw %form
use form_tag
or better form_for
when it's possible (or more better simple_form or formtastic)
另外,在可能的情况下使用form_tag或更好的form_for而不是raw%form(或者更好的simple_form或formtastic)
#1
16
Something like this will work (using the older "hashrocket syntax" with the operator =>
)
像这样的东西将起作用(使用较旧的“hashrocket语法”与operator =>)
%select
%option{:value => "a", :selected => params[:x] == "a"}= "a"
%option{:value => "b", :selected => params[:x] == "b"}= "b"
Or, in newer Ruby versions (1.9 and greater):
或者,在较新的Ruby版本(1.9及更高版本)中:
%select
%option{value: "a", selected: params[:x] == "a"}= "a"
%option{value: "b", selected: params[:x] == "b"}= "b"
#2
13
You should unleash the power of rails helpers.
你应该释放铁路助手的力量。
对于选择标签:
= select_tag :param_name, options_for_select([['A data', 'A'], ['B data', 'B']], params[:param_name])
Also, instead of raw %form
use form_tag
or better form_for
when it's possible (or more better simple_form or formtastic)
另外,在可能的情况下使用form_tag或更好的form_for而不是raw%form(或者更好的simple_form或formtastic)