问题描述
我是 Elixir 的新手,无法以 DRY 方式呈现此组件。我有这个 CardHeader 组件
<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)"}}
/>
可能有也可能没有@truck_load.measured_weight 值。如果是这样,我希望将 info 变量设置为其值,并使用字符串插值来显示测量单位。 如果没有@truck_load.measured_weight 值,我不希望出现测量单位,所以我希望将 info 设置为空字符串。
如果没有单独的 CardHeader 组件来检查 @truck_load.measured_weight 是否为 nil,我无法弄清楚如何使其正常工作:
<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=""
/>
有没有更好、更干燥的方法来做到这一点?
谢谢!!
解决方法
就像分成 2 个组件
<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>