Rails template conditions

时间秒杀一切 提交于 2020-01-06 02:11:28

问题


In PHP I did template consitions with such code:

<?php if($item['taste'] > 0):?>taste_plus<?php elseif($item['taste'] == 0):?>taste_zero<?php else:?>taste_minus<?php endif;?>

And I did number formatting with <?php echo number_format($item['taste'], 2)?> for fetch them to "2.00" format.

How to do things like that in Rails templates?


回答1:


A direct translation of your template code would look something like this:

<% if @item.taste > 0 %>taste_plus<% elsif @item.taste == 0 %>taste_zero<% else %>taste_minus<% end %>

In this example, I've made the code more object-oriented and used the @item member variable, which is more Ruby/Rails-like, rather than use a PHP array to transfer variables to the HTML template.

However, rather than use this direct translation, a Rails developer would more likely try to reduce the need to have so much logic in the template by making a helper function like this:

def taste_helper(taste)
  if taste > 0
    taste_plus
  elsif taste == 0
    taste_zero
  else
    taste_minus
  end 
end

... So that she could put this in her template:

<%= taste_helper(@item.taste) %>

For formatting numbers in your template you could use the Rails number_with_precision function like this:

number_with_precision(2, :precision => 2)

The above formatting function would output '2.00'. The docs for number_with_precision() are here.



来源:https://stackoverflow.com/questions/5130001/rails-template-conditions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!