Is there a way of breaking out of an "if" section

I’m not sure the topic title explains very well what I want to do. Essentially, I have a touchscreen display running of an ESP32 Wrover module, and I want to toggle between screens using the touch.

At the moment, I tried this:

    on_release:
      - if:
          condition:
            display.is_displaying_page: page1
          then:
            - display.page.show: page2
            - component.update: tft_ha
      - if:
          condition:
            display.is_displaying_page: page2
          then:
            - display.page.show: page1
            - component.update: tft_ha

Unfortunately, when it runs the actions from meeting the first condition, it then meets the second condition and runs that.

Is there a way of breaking out ?

I can get it to work like this, but it’s going to look really nasty when I start adding more pages:

    on_release:
      - if:
          condition:
            display.is_displaying_page: page1
          then:
            - display.page.show: page2
            - component.update: tft_ha
          else:
          - if:
              condition:
                display.is_displaying_page: page2
              then:
                - display.page.show: page1
                - component.update: tft_ha

Many thanks.

You probably wish to use a ‘case’ statement or its equivalent.
I’m not aware of ESPhome having such a statement, so a cascade of if/then/elseif/then/elseif/… may be the only option for achieving the same logic using ESPHome config syntax.
But, if you translate the action into a lambda, you would then be able to use C++'s case statement within it.

1 Like

Replacing both instances of “if” with “while” should do it in this case. You can easily add more pages after that. never mind, same problem as with “if” :wink:

as glyndon said, a lambda is probably your best bet.

1 Like

Thanks to you both. I had no idea how to call the display.page.show from a lambda, but the docs had an example of how to use a lambda to return the parameter to use. So, I removed the need to use “is_displaying_page” by adding a global, then changed it to this:

    on_press:
      - display.page.show: !lambda |-
          if (id(page_id) == 0) {
            id(page_id) = 1;
            return id(page1);
          } else {
            id(page_id) = 0;
            return id(page1);
          }
      - component.update: tft_ha

I will change it to use a case statement when I have more pages.
(I also changed it to on_press rather than on_release)

Thanks again.

1 Like