Need Help in fixing the jinja2 script execution issue for setting fan icon speed

I am trying to set the fan icon rotation speed based on fan speed percentage. The below jinja2 code is not being executed/ no action performed (i.e. fan icon is not rotating). Kindly help me in identifying and fixing the issue.

        state:
          - value: 'on'
            styles:
              icon: >
                - {% set speed = state_attr('fan.livingroom_fan_2_2',
                'percentage') | int(0) %}
                  {% if speed > 0 %}
                    animation: rotating {{ 100 / speed if speed > 0 else 0 }}s linear infinite
                  {% else %}
                    animation: none
                  {% endif %}                    
          - value: 'off'
            styles:
              icon:
                - animation: null

What you posted seems like a code for a custom button card (not mentioned in your post) with jinja templates (which are not supported by this card). The card supports templates in JS, see examples in the card Docs.

1 Like

You are correct. It’s a custom button card. Let me try to rewrite this in JS. Thanks for your help!!

Kind of

animation: >-
  [[[
    if (…)
      return “…..”;
    else
      return “none”;
  ]]]
1 Like

Noob question. I am getting “Unable to parse YAML: YAMLException: missed comma between flow collection entries” error for below modified code with JS. Am I missing something?

        state:
          - value: 'on'
            styles:
              icon: 
                - animation: |
                  [[[
                    if (entity.attributes.percentage == 0) {
                      return 'none';
                    } else if (entity.attributes.percentage <= 33) {
                      return 'rotating 2s linear infinite';
                    } else if (entity.attributes.percentage <= 66) {
                      return 'rotating 1s linear infinite';
                    } else {  
                      return 'rotating .5s linear infinite';
                    }  
                  ]]]                   
          - value: 'off'
            styles:
              icon:
                - animation: none

Try indent the “[[[…]]]” part.

1 Like

Thank you for your help!! Below is the working code for icon rotation based on selected fan speed.

        state:
          - value: 'on'
            styles:
              icon:
                - animation: |
                    [[[
                      const speed = entity.attributes.percentage;
                      if (speed > 0) {
                        return `rotating ${50/speed}s linear infinite`;
                      } else {  
                        return 'none';
                      }  
                    ]]]                   
          - value: 'off'
            styles:
              icon:
                - animation: none
2 Likes

Please mark your post as a solution to help other people.

1 Like