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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With