问题
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