MQTT Sensor Template error

Trying to sort out an mqtt sensor template issue. What I have is:

mqtt:
  sensor:
    - name: weewx_wind_dir
      unique_id: weewx_wind_dir
      state_topic: "weather/loop"
      unit_of_measurement: "º"
      value_template: >
        {% if value_json.windDir %}
          {{ value_json.windDir | round(0) }}
        {% endif %}

The issue is that when the wind speed is 0, the windDir is not sent in the mqtt message. No wind - No direction. However the wind speed does report with 0.0.
I would think that the if value_json windDir would prevent the sensor update but I get the following warning in the logs.

Template variable warning: 'dict object' has no attribute 'windDir' when rendering '{% if value_json.windDir %} {{ value_json.windDir | round(0) }} {% endif %}'
8:52:52 AM – (WARNING) helpers/template.py - message first occurred at 8:48:50 AM and shows up 3 times

Any thoughts on using a value_template that would eliminate this error?
Cheers

It’s telling you that windDir doesn’t exist in value_json, but you’re testing its value. You probably need this:

      value_template: >
        {% if windDir in value_json %}
          {{ value_json.windDir | round(0) }}
        {% endif %}

You also have no else clause there, so it will evaluate to nothing and fail if windDir isn’t found. You should add an availability section or an else to ensure that the sensor always has a value.

Thank you! Your code clears my error. I am having problems formatting a correct else but that is just me. So I am looking into proper usage of the availability you mentioned.

Thanks again and cheers.

Note for reference… Had to add quotes around json IF test

{% if "windDir" in value_json %}

That’s what solved it for me.