0

Here's the thing. I have a button that, depending on the scenario, will behave, look and have different text. Here's how it, roughly, looks like at the moment:

- if params[:param_A] && @statement_A
  %span.button.cancel_button{attribute: "value_B"}
    - if @statement_B
      = t('locale_A')
    - else
      = t('locale_B')
- elsif params[:param_A]
  %span.button.cancel_button{attribute: "value_A"}
    - if @statement_B
      = t('locale_A')
    - else
      = t('locale_B')

There's also a CSS class both buttons should have IF statement_B is true.

So it is a mess. And I recently read about the "Tell, don't ask" principle which I liked very much, so I'd love to apply it here... but I'm not sure how.

I know I could make a helper, but I'd like to stay away from them because reasons (I really have some valid reasons to do so, but those are beyond the scope of this question). I can resort to that as a last resource, but would rather find another solution.

  • The question is, why are you putting your conditional logic inside the HAML template, instead of in your controller? You know more about the situation inside the controller than you do in the view, so compute your values before handing off control. In the view you just render the output, with very little need to use conditional tests. – the Tin Man Oct 03 '12 at 22:44
  • I agree with @theTinMan, this kind of conditional logic shouldn't be in your view. Either work it out in the controller or at least put it into a helper. – dnatoli Oct 03 '12 at 23:58

1 Answers1

1

This is not really related to haml. You can start with the way how your example should look with tekll-don'r ask:

- if params[:param_A] 
  %span.button.cancel_button{attribute: @object1.value}
    = t(@object2.locale)

or

- if params[:param_A] 
  %span.button.cancel_button{attribute: @object.value}
    = t(@object.locale)

(depending on your preference / what really statement A/B mean)

For this to work you'd need to initialize object(s) prior to rendering, based on statement value.

UncleGene
  • 2,132
  • 16
  • 19
  • +1 for "For this to work you'd need to initialize object(s) prior to rendering, based on statement value." The objects should be figured out in the controller, before being passed to the view. – the Tin Man Oct 03 '12 at 22:45