[英]Rails form (select/option) - how to mark selected option with HAML?
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... 但这在
select
框将包含许多选项字段时是不合适的...
Something like this will work (using the older "hashrocket syntax" with the operator =>
) 这样的事情会起作用(将早期的“ hashrocket语法”与运算符
=>
)
%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"
You should unleash the power of rails helpers. 您应该释放Rails助手的力量。
= 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) 此外,在可能的情况下(或更好的simple_form或formtastic),可以使用
form_tag
或更好的form_for
代替raw %form
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.