Ada*_*dam 2 ruby-on-rails erb concatenation
在index.html.erb中,我希望每个大学的链接看起来如下: 申请 - 25美元
我希望显示的价格根据college.undergrad_app_fee的值而变化.
这是我尝试过的,但它不起作用.也许有一种特殊的连接语法可以将显式的"应用 - "与价格结合起来,或者我需要以某种方式逃避<%=%>,或者有一种特殊的方法可以用link_to来做到这一点?
<td><%= link_to 'Apply - ' college.undergrad_app_fee, college.application_url %></td>
Run Code Online (Sandbox Code Playgroud)
Ben*_*ret 12
使用字符串插值语法:
<td><%= link_to "Apply - #{college.undergrad_app_fee}", college.application_url %></td>
Run Code Online (Sandbox Code Playgroud)
作为奖励,如果您只有原始价格,您可以使用number_to_currency以下格式进行格式化:
<td><%= link_to "Apply - #{number_to_currency(college.undergrad_app_fee)}", college.application_url %></td>
Run Code Online (Sandbox Code Playgroud)
跟进:
对于条件链接,使用link_to_if或link_to_unless,它们应该相对简单易用.
处理nil货币格式的情况有点棘手.您可以使用||运算符来执行此操作.
结合这两种方法可以得到:
<td><%= link_to_if college.application_url, "Apply - #{number_to_currency(college.undergrad_app_fee || 0)}", college.application_url %></td>
Run Code Online (Sandbox Code Playgroud)
使用rails控制台是测试不同帮助程序行为的好方法.您可以通过helper对象访问它们,例如:
> helper.number_to_currency(12)
=> "12,00 €"
> nil || 0
=> 0
> 12 || 0
=> 12
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3797 次 |
| 最近记录: |