diff --git a/esphome/components/template/text/template_text.cpp b/esphome/components/template/text/template_text.cpp index 32ed8f047b..5acbb6e15a 100644 --- a/esphome/components/template/text/template_text.cpp +++ b/esphome/components/template/text/template_text.cpp @@ -8,16 +8,23 @@ static const char *const TAG = "template.text"; void TemplateText::setup() { if (this->f_.has_value()) return; - std::string value = this->initial_value_; - if (!this->pref_) { - ESP_LOGD(TAG, "State from initial: %s", value.c_str()); - } else { - uint32_t key = this->get_preference_hash(); - key += this->traits.get_min_length() << 2; - key += this->traits.get_max_length() << 4; - key += fnv1_hash(this->traits.get_pattern_c_str()) << 6; - this->pref_->setup(key, value); + + if (this->pref_ == nullptr) { + // No restore - use const char* directly, no heap allocation needed + if (this->initial_value_ != nullptr && this->initial_value_[0] != '\0') { + ESP_LOGD(TAG, "State from initial: %s", this->initial_value_); + this->publish_state(this->initial_value_); + } + return; } + + // Need std::string for pref_->setup() to fill from flash + std::string value{this->initial_value_ != nullptr ? this->initial_value_ : ""}; + uint32_t key = this->get_preference_hash(); + key += this->traits.get_min_length() << 2; + key += this->traits.get_max_length() << 4; + key += fnv1_hash(this->traits.get_pattern_c_str()) << 6; + this->pref_->setup(key, value); if (!value.empty()) this->publish_state(value); } diff --git a/esphome/components/template/text/template_text.h b/esphome/components/template/text/template_text.h index 178b410ed2..e5e5e4f4a8 100644 --- a/esphome/components/template/text/template_text.h +++ b/esphome/components/template/text/template_text.h @@ -70,13 +70,15 @@ class TemplateText final : public text::Text, public PollingComponent { Trigger *get_set_trigger() const { return this->set_trigger_; } void set_optimistic(bool optimistic) { this->optimistic_ = optimistic; } - void set_initial_value(const std::string &initial_value) { this->initial_value_ = initial_value; } + void set_initial_value(const char *initial_value) { this->initial_value_ = initial_value; } + /// Prevent accidental use of std::string which would dangle + void set_initial_value(const std::string &initial_value) = delete; void set_value_saver(TemplateTextSaverBase *restore_value_saver) { this->pref_ = restore_value_saver; } protected: void control(const std::string &value) override; bool optimistic_ = false; - std::string initial_value_; + const char *initial_value_{nullptr}; Trigger *set_trigger_ = new Trigger(); TemplateLambda f_{};