Rails 模板条件 [英] Rails template conditions

查看:53
本文介绍了Rails 模板条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 PHP 中,我用这样的代码做了模板条件:

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;?>

我使用 <?php echo number_format($item['taste'], 2)?> 进行数字格式化,以便将它们提取为2.00"格式.

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

如何在 Rails 模板中做类似的事情?

How to do things like that in Rails templates?

推荐答案

模板代码的直接翻译如下所示:

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 %>

在这个例子中,我使代码更加面向对象,并使用了@item 成员变量,它更像 Ruby/Rails,而不是使用 PHP 数组将变量传输到 HTML 模板.

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.

然而,Rails 开发人员更可能会尝试通过创建这样的辅助函数来减少模板中有如此多逻辑的需要,而不是使用这种直接翻译:

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) %>

为了格式化模板中的数字,您可以使用 Rails number_with_precision 函数,如下所示:

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

number_with_precision(2, :precision => 2)

上述格式化函数将输出2.00".number_with_precision() 的文档在这里.

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

这篇关于Rails 模板条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆