Rails switch case in the view

匿名 (未验证) 提交于 2019-12-03 01:47:02

问题:

I want to write a switch case in my view :

               "one") %>          "two") %>          "three") %>       

But it doesn't work. Do I have to add a somewhere in each line ? Any ideas ? Thanks !

回答1:

You should pull your first when into same block as case

    "one") %>    "two") %>    "three") %>     


回答2:

Don't put to much logic in your views.

i would add a helper

def humanize_number(number)     humanized_numbers = {"0" => "zero", "1" => "one"}     humanized_numbers[number.to_s] end 

than you can call it from the view with

 humanized_number(index)) %> 


回答3:

First, you should really think about abstracting this functionality into a helper method to avoid cluttering your views with logic.

Second, case statements are a bit tricky to use in ERB, because of the way erb parses the code. Try instead (not tested, as I don't have a ruby close to hand at the moment):

           "one") %>             "two") %>             "three") %>     

See this thread for more information.



回答4:

You can also use syntax:

       "one") %>        


回答5:

This helped with whitespace for me.

 


回答6:

I think in ERB, you'll have to put the conditions on the line under the whens. Like this:

                "one") %>             "two") %>             "three") %>     

Ruby supports case-whens with one line conditions with the then keyword, but I don't think ERB can parse them correctly. Ex:

case index     when 0 then "it's 0"     when 1 then "it's 1"     when 2 then "it's 2" end 


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