Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I DRY up this Haml?

I'm working in a Rails application, and I've got this Haml repeating about a dozen times. How can I refactor this? I feel like a helper would be great for this, but I'm really not sure what code should go in the helper.

- if @object.thing
  .row
    .col-md-12
      .campaign-summary-title Thing
      = render text: @campaign.thing.html_safe
- if @object.thing2
      .row
        .col-md-12
          .campaign-summary-title Thing2
          = render text: @object.thing2.html_safe

I found this, but it's not really the same question: Dont show field if blank Rails

like image 684
jacobherrington Avatar asked Nov 28 '25 01:11

jacobherrington


1 Answers

You could use a partial. Your partial (_partial_name.html.haml) would look like:

- if @object[field]
  .row
    .col-md-12
      .campaign-summary-title= field.capitalize
        = render text: @object[field].html_safe

That allows you to use this code in different files, calling it like:

= render partial: "partial_name", field: "thing"
= render partial: "partial_name", field: "thing2"

And in case that there are many fields you could for example write it like :

- ["thing", "thing2"].each do |field|
  = render partial: "partial_name", field: field
like image 182
Ana María Martínez Gómez Avatar answered Nov 29 '25 18:11

Ana María Martínez Gómez