0

I am new to elixir and having trouble rendering this component in a DRY way. I have this CardHeader component

    <CardHeader
      :if={{ not is_nil(@truck_load.sand_type) }}
      background_color={{ @truck_load.sand_type_background_color }}
      text_color={{ @truck_load.sand_type_text_color }}
      title={{ @truck_load.sand_type }}
      :if={{ not is_nil(@truck_load.measured_weight) }}
      info={{"#{@truck_load.measured_weight} lb (#{
      Weight.convert_pounds_to_tons_and_round(@truck_load.measured_weight, 2)
      } tons)"}}
    />

that may or may not have a @truck_load.measured_weight value. If it does, I want the info variable to be set to its value, with string interpolation to show the units of measurement. If there is no @truck_load.measured_weight value, I don't want the units of measurement to appear, so I want info to be set to an empty string.

I can't figure out how to get this to work without having a separate CardHeader component that checks if @truck_load.measured_weight is nil like so:

<CardHeader
          :if={{ not is_nil(@truck_load.sand_type) }}
          background_color={{ @truck_load.sand_type_background_color }}
          text_color={{ @truck_load.sand_type_text_color }}
          title={{ @truck_load.sand_type }}
          :if={{ is_nil(@truck_load.measured_weight) }}
          info=""
        />

Is there a better, DRYer way to do this?

Thanks!!

Eyeslandic
  • 14,553
  • 13
  • 41
  • 54

1 Answers1

0

Just separate into 2 Components like

    <SandType
      background_color={{ @truck_load.sand_type_background_color }}
      text_color={{ @truck_load.sand_type_text_color }}
      title={{ @truck_load.sand_type }}
    />

    <WeightType
      info={{"#{@truck_load.measured_weight} lb (#{
      Weight.convert_pounds_to_tons_and_round(@truck_load.measured_weight, 2)
      } tons)"}}
    />
    <CardHeader>
      <SandType :if={{ not is_nil(@truck_load.sand_type) }} />
      <WeightType :if={{ not is_nil(@truck_load.measured_weight) }} />
    </CardHeader>
Minh-Khang
  • 414
  • 2
  • 10