Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep haml code in a variable and use it then

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.

like image 650
edudepetris Avatar asked Feb 14 '23 12:02

edudepetris


1 Answers

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.

like image 178
matt Avatar answered Feb 23 '23 23:02

matt