I’m used to just using a single unit of measurement for each sensor template like the below sample code. However, I’d like for the unit of measurement to automatically change from MB to GB if the respective value is more than 1024.
Is this possible? I’m almost certain the below code is wrong since I was getting a syntax error in the template editor. However, I thought I’d at least post something (even if its wrong) rather than nothing at all:
process_0_virt:
value_template: >
{% set process_0_virt = (state_attr('sensor.processlist0', 'memory_info'))[0] %}
{% set value = ((process_0_virt / 1024) / 1024) | round(1) %}
{{ value }}
availability_template: >-
{{ states('sensor.processlist0') not in ["unknown", "unavailable", "none"] }}
{% if (value <= 1024 ) %}
{{ unit_of_measurement: "MB" }}
{% elif (value > 1024 ) %}
{{ unit_of_measurement: "GB" }}
For display purposes you could have a master MB sensor and a template GB sensor tracking it, then choose which one to display using e.g. conditional rows on an entities card.
Thanks for the quick response. I didn’t understand when you said “a template GB sensor tracking it,”. Can you give me an example considering below MB sensor is what I have to start with? I’m using a Markdown card, so hopefully, I’ll be able to figure out how to apply to condition between the 2 in my Markdown card. Thank you for your time.
You can only use templates to set the value of a key: value pair. Your template attempts to return both key and value, {{ unit_of_measurement: "MB" }}
You can’t use the availability template to set anything other than the availability of the template sensor. It must only return a result of true or false.
The unit_of_measurement does not accept templates.
I really appreciate it. I have dozens of legacy templates I need to upgrade to the new template integration. I’ve been putting it off from a while now. I’ll use your examples here to help me migrate all my templates over to the new standard. I can either use your suggested solution or @tom_l 's solution. Both of your responses were very helpful to me.