jacobherrington
jacobherrington

Reputation: 463

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

Upvotes: 3

Views: 162

Answers (2)

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

Upvotes: 3

jvillian
jvillian

Reputation: 20263

How about something like:

- [:thing, :thing2].each do |thing_sym|
  - if @object.send(thing_sym)
    .row
      .col-md-12
        .campaign-summary-title #not sure what you want here
        = rendertext: @campaign.send(thing_sym).html_safe

You'll have to fuss with the title bit as it's unclear how you want to derive Thing, Thing2, etc.

Upvotes: 1

Related Questions