thank_you
thank_you

Reputation: 11107

Fixing redundancy in Slim if else statement

I have the following if else statement in my slim file

- if x == 0
 div Some cool title here
- else
 div A different cool title goes here

Which is fine, however I want to have some child tags inside the divs

- if x == 0
 div Some cool title here
   div Ditto
- else
 div A different cool title goes here
   div Ditto

This is going against DRY. Is there anyway I can reduce this code so I don't have to see the child tags twice? Any attempt I've made so far has lead me to have the child tag exist in one div and not the other which is not what I want, I want the child tag to exist no matter what.

Upvotes: 0

Views: 3629

Answers (2)

Billy Chan
Billy Chan

Reputation: 24815

Three levels solutions:

  1. if/else in template like your original code. Use case: short code

  2. Use helper. I like this. Use case: longer but not too long code with apparent pattern.

    = my_helper(x)
    

    Then in helper you can interpolate x. Very powerful.

  3. Use if/else and partial. As Alex already mentioned. Use case: Long code after if or else.

Upvotes: 1

Alex Peachey
Alex Peachey

Reputation: 4686

When duplicating code in a view, you should use a partial to hold that duplicated code and render the partial where ever you want it to appear. I know your simplified code is just to show your intent but if it was more real I could provide even further suggestions.

You can also inline that logic:

div
  = x == 0 ? 'Some Cool Title' : 'Some Other Title'
  div Ditto

Better than that though would be to move that logic into somewhere more suitable like use a gem like Draper to create a presenter object.

div
  = @my_presenter_object.title
  div ditto

Upvotes: 3

Related Questions