How to use Variables in MQTT Publish

Good afternoon All,
This must have been answered before and I am not good enough with my google searches.
But lets say I have value from a sensor and I want to publish to an mqtt topic ( not the system sent one ) but a completely new topic.
This fails of course, but for the life of me I cannot google a preferred way.

# BME 280 Sensor
  - platform: bme280
    address: 0x76
    update_interval: $update_interval
      name: "Temperature"
      id: bme280_temperature

  - interval: 5s
      - mqtt.publish:
          topic: /sensors/nodemcu-1/bmetemperature
          payload: id(bme280_temperature).state

This produces : /sensors/nodemcu-1/bmetemperature id(bme280_temperature).state as expected.

How / What is the best way to turn the variable into a value that can be published.

Apologies if this is a real newbie question and you need to provide a How to Google link, but its a learning curve for me.

Thanks again

The simplest way to send sensor values from ESPHome via MQTT is using the default method (without mqtt.publish), but this works as well, using a lambda:

      - mqtt.publish:
          topic: /sensors/nodemcu-1/bmetemperature
          payload: !lambda |-
            return esphome::to_string(id(bme280_temperature).state);

The advantage of this method could be that you have more control over the topic structure.

1 Like

Thank you for your help. That has worked perfectly and yes gets me control over the payload and topics.

I did want to change the fixed decimal places and my Google searching worked this time. My new code looks like this. Again is the best way to achieve such an output

      - mqtt.publish:
          topic: /sensors/nodemcu-1/bmetemperature
          #value_template: '{{value | round(1) }}'
          payload: !lambda |-
                // return esphome::to_string(id(targetTemp));
                char buf[128];
                sprintf(buf, "%.2f", id(bme280_temperature).state);
                return buf;