Question

I want to do somethings like this and I don't know if it's possible. Also I know this isn't a good practice but I am in a deadline.

In my _buttons.html.haml

- buttons = case params[:action]
- when 'edit'
  %a.property-save{ href: "#" }
    %i.icon-save.icon-2x
    = t('.property_save')
  ...
- when 'show'
  ...
- else
  %a.property-save{ href: "#" }
    %i.icon-open.icon-2x
    = t('.property_open')

.my-butons
  = buttons

The problem is the html code is rendered and I don't know how I put on these code inside the buttons variable. Thanks for your advice.

Was it helpful?

Solution

The direct way to do what you want is to use the capture_haml helper to capture a block into a string to reuse later:

- buttons = case params[:action]
- when 'edit'
  - capture_haml do
    %a.property-save{ href: "#" }
      %i.icon-save.icon-2x
      = t('.property_save')
    ...
- when 'show'
  - capture_haml do
    ...
- else
  - capture_haml do
    %a.property-save{ href: "#" }
      %i.icon-open.icon-2x
      = t('.property_open')

.my-butons
  = buttons

You do seem to have a lot of repetition in the block, a better way might be something like:

.my-buttons
  %a.property-save{ href: "#" }
    %i.icon-2x{:class => "icon-#{params[:action]}"}
    = t(".property_#{params[:action]}")

You’d have to adapt this to your real data, but note the value of the class attribute will be formed by merging the icon-2x and the result of the hash, so you can avoid some duplication.

OTHER TIPS

Assign value to buttons inside your when statements. And avoid doing these logic in Views.

- case params[:action]
- when 'edit'
  %a.property-save{ href: "#" }
    %i.icon-save.icon-2x
    - buttons = t('.property_save')
- else
  %a.property-save{ href: "#" }
    %i.icon-open.icon-2x
    - buttons = t('.property_open')

.my-butons
  = buttons
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top