开发者

Ruby / Rails: only pass parameter if condition is true

开发者 https://www.devze.com 2023-02-19 15:01 出处:网络
I have a line of HAML like this: %li{:id=>node.shortcode, :class=>liclass unless liclass.empty? }

I have a line of HAML like this:

%li{:id=>node.shortcode, :class=>liclass unless liclass.empty? }
开发者_运维技巧

which doesn't work. I only want to pass the 'class' parameter if the condition provided isn't true. Is there a nice way to do this in Ruby will I just have to use an if/else?


Try this:

%li{({:id=>node.shortcode}.merge(liclass.empty? ? {} : {:class=>liclass}) )}

It's not pretty, but it gives you the markup you're after.


%li{:id=>node.shortcode, :class=>(liclass unless liclass.empty?)}


It shouldn't assign class when liclass will be empty, but I'm not sure.
Try this:
%li{:id=>node.shortcode, :class=>liclass }

0

精彩评论

暂无评论...
验证码 换一张
取 消