简体   繁体   中英

how to avoid using the same condition twice in slim views

I have the following code in my view:

.container
  .row
    .col
      h3 Header
      - if @status < 5
        p Text
    - if @status < 5
      .col
        p More text

As you can see I use the same condition two times because of slim indentation. Is there any way to avoid this?

The only thing I think you can do is refactor it.

Use a helper instead of hardcoded condition everywhere, so that when you decide to change 5 to 6 you will have to make the change at one place only.

Helper method

def valid_status?(status)
  status < 5
end

view (slim)

.container
  .row
    .col
      h3 Header
      - if valid_status?(@status)
        p Text
    - if valid_status?(@status)
      .col
        p More text

Or at least assign the value to a variable once

- valid_status = @status < 5
.container
  .row
    .col
      h3 Header
      - if valid_status
        p Text
    - if valid_status
      .col
        p More text

You need to extract the conditional to a helper like Deepak suggested and use a partial render to extract the html snippet. More or less like this:

.container
  .row
    .col
      h3 Header
        = render "render_text_1" if status_5? # Humanize status code to be more clear
    .col
      = render "render_text_2" if status_5?

好像这个标记没什么问题,所以最好的解决方案是保持原样。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM