diff --git a/esphome/yaml_util.py b/esphome/yaml_util.py index 19bbca61f8..520379e51d 100644 --- a/esphome/yaml_util.py +++ b/esphome/yaml_util.py @@ -755,6 +755,11 @@ class ESPHomeDumper(yaml.SafeDumper): return self.represent_scalar(tag="!remove", value=value.value) def represent_include_file(self, value): + if value.vars: + mapping = {"file": value.file.as_posix(), "vars": value.vars} + return self.represent_mapping( + tag="!include", mapping=mapping, flow_style=False + ) return self.represent_scalar(tag="!include", value=value.file.as_posix()) def represent_id(self, value): diff --git a/tests/unit_tests/test_yaml_util.py b/tests/unit_tests/test_yaml_util.py index a918e521d8..2c01019abd 100644 --- a/tests/unit_tests/test_yaml_util.py +++ b/tests/unit_tests/test_yaml_util.py @@ -516,6 +516,20 @@ def test_represent_include_file() -> None: assert yaml_util.dump({"key": include}) == "key: !include 'path/to/file.yaml'\n" +def test_represent_include_file_with_vars() -> None: + """Test that IncludeFile with vars is dumped as !include mapping form.""" + include = yaml_util.IncludeFile( + Path("/fake/main.yaml"), + "path/to/file.yaml", + {"key": "value"}, + lambda _: {}, + ) + result = yaml_util.dump({"key": include}) + assert "!include" in result + assert "file: path/to/file.yaml" in result + assert "key: value" in result + + def test_represent_include_file_with_data_base_mixin() -> None: """Test that IncludeFile wrapped with ESPHomeDataBase mixin is also dumped correctly.