Define a color constant for and reuse code within a template card

Dear all,

I have created following code to evaluate what color to be used in presenting an icon for a mushroom chips template card. This works nicely but it is a little bit awkward as I have copied the code 15 time…

      {% set state=states(entity) %}
      {% if state=='off' %}
      {% elif state=='on' %}
      {% else %}
      {% endif %}

There fore I have two questions:
1 How to define a constant for the color values to be used accross dashboards and cards
2 is there a way to avoid copying the code for each and every card. Not sure if anchors will work here…

Thank you all