Lambda pages // Define and retrieve repetitive code

Hello everyone

I use an RGB matrix in ESPHome and have set up several pages there. I have programmed two scroll animations and am looking for a solution so that I can call them on additional pages (since it is a rather long code) and I do not have to insert this completely on each page again. I would then only like to define the ID of the image, the sensor and the string on the pages

Here is my example:

display:
  - platform: matrix_display
    id: matrix
    width: 64
    height: 32
    chain_length: 2
    brightness: 64
    pages:
- id: page3

        lambda: |-

          it.strftime(128, 1, id(clock_time), id(greenyellow), TextAlign::RIGHT, "%H:%M:%S", id(hass_time).now());

          //it.printf(32, 31, id(clock_font), id(red), TextAlign::BOTTOM_CENTER, "%.0f ppm", id(co2_stube).state);

         

          // Scrollender Text (Sensorwert)

          std::string scrolling_text = "%.0f ppm";  // Verwende std::string "%.0f ppm", id(co2_stube).state);

          int font_size = 12;

          int scrolling_text_width = scrolling_text.length() * font_size;

          int text_start_x = 128;

          int text_end_x = 35;

          int text_max_x_scroll = 35;

          static int current_x_scroll_text = text_start_x;

          int text_scroll_speed = 1;

          // Überprüfen, ob die Flagge für den Seitenwechsel nicht gesetzt ist

          if (id(page_switch_flag) == true) {

              current_x_scroll_text = 128;

              //id(page_switch_flag) = false; // Zurücksetzen der Flagge

          }

          int text_y_position = 31;

          it.printf(current_x_scroll_text, text_y_position, id(clock_font), id(red), TextAlign::BOTTOM_LEFT, scrolling_text.c_str(), id(co2_stube).state);

          current_x_scroll_text -= text_scroll_speed;

          if (current_x_scroll_text < text_max_x_scroll) {

              current_x_scroll_text = text_max_x_scroll; // Setzen Sie die Position zurück, um erneut von x128 zu starten

          }

          // Scrollendes Bild

         *static int current_x_scroll = 0;

          int max_x_scroll = 31;

          if (id(page_switch_flag) == true) {

              current_x_scroll = 0;

              id(page_switch_flag) = false; // Zurücksetzen der Flagge

          }

          int y_position = 0;

          it.image(current_x_scroll, y_position, id(bitmap_co2_stube), ImageAlign::RIGHT);

          current_x_scroll++;

          if (current_x_scroll > max_x_scroll) {

              current_x_scroll = max_x_scroll;

          }

Unfortunately, I have not yet been successful in implementing this. Can anyone help me with how to proceed? I have tried substitutions and globals and was not successful. I think it would not be that difficult so I am asking here.

Best regards