#templates-archived
1 messages · Page 116 of 1
np; it's probably something pretty well known to the python coders out there. I'm just really bad with them as well lol
its limited to a subset of stuff and i hate dealing with it in python as it is
no question it's a headache.
is there a next game date property?
There is, but I can't seem to get it to work with strptime. If I could figure out how to add a new attribute to the custom sensor that I'm using I'd create an attribute that would work.
what are the attributes on the original sensor?
might be able to merge a few properties to get it to work
That'd be great. Here's my github where I forked it. I figured I'd do a PR on the original version because it might help the dev a bit.
I already fixed the time variable at line 92 so that I could get the space between the time and "PM" which made strptime work. But really if I could just expose dttm_local (at 91) as an attribute to HA I could probably work from there
looks like you have next_game_date and next_game_time that you could use
I do, but I've tried to merge next_game_date and next_game_time together in strptime and it doesn't accept them as a valid date/time string
e.g. {{ strptime(state_attr ('sensor.leafs_game', 'next_game_date') + ", " + state_attr('sensor.leafs_game','next_game_time'), '%I:%M %p') }} doesn't actually return a timestamp
could try this:
{{ strptime(next_game, '%B %-d, %Y %-I:%M %p') }}```
That returns the merged date, but as_timestamp on that final strptime returns "none". I'm pretty sure I need to go to as_timestamp to add 5 minutes
nah,
{{ strptime(next_game, '%B %-d, %Y %-I:%M %p') + timedelta(minutes=5) }}
TypeError: can only concatenate str (not "datetime.timedelta") to str
Yeah. I think we're at what I said - I don't think that next_game is rendering in a format that strptime recognizes as a time/date format
while you're making changes, why not add the raw timestamp to the attributes
That's kind of what I was thinking. I'm going to have to follow the developers documentation - I don't know how to add the attribute. I assume that the change is made in the dict defined at 111 but I'm not quite there yet
i'd add it to the time dict at 92
time = {
'next_game_time': dttm_local.strftime('%-I:%M %p'),
'next_game_datetime': dttm_local
}
might need to define some sort of format
worth a test
Sweet. I will. I'll play around with it a bit more. Thanks phnx I really appreciate your help.
I'll give it a shot. Have to go AFK for a few minutes but I'll let you know where I get when I get back.
https://pastebin.ubuntu.com/p/QzVvD9kK3z/ - how can i run this script for a single entity and put results in a card?
how can i parse an rgb json value? cant get it to work...
{
"state": "ON",
"color": {
"r": 255,
"g": 118,
"b": 72
}
}
i KNOW there is one thread in the forum. but google dont like me today.
action:
- service_template: light.turn_{{ trigger.payload_json.state | lower }}
data_template:
entity_id: "{{ trigger.topic.split('/')[2] }}.{{ trigger.topic.split('/')[3]}}_{{ trigger.topic.split('/')[4] }}_{{ trigger.topic.split('/')[5] }}"
color: "{{ trigger.payload_json.color }}"
something about a value template and then fetching the tree values from the payload....
{{trigger.payload_json.color.r}} and so on
Just like {{trigger.payload_json.state}} in your second line there.
needs to be a tuple or a list? i can't remember
then is maybe something above false. let me check.
i have tried color: [{{ trigger.payload_json.color.r }}, {{ trigger.payload_json.color.g }}, {{ trigger.payload_json.color.b }}]
{{ trigger.payload_json.color.values()|list }}
have it!
color rgb_color: [{{ trigger.payload_json.color.r }}, {{ trigger.payload_json.color.g }}, {{ trigger.payload_json.color.b }}]
Do you even need the list filter?
does not work.
wrap it in "
yeah, that would make a list of a list
Yes, you do.
yeah, it returns a dict_values which gets dumped as a string unfortunately
not a native type
super nice here. 😄 u guys helped me alot.
from every light with all values as automation (6 per light) to just a single template per value (6 in total). 😛
and now i can add even more without writing more automations. 😛
😛
I'm all for reducing automation numbers.
and the native type outputs from template has been pretty huge for template complexity
Oh yes
With that and the recent changes to automations, automations are almost a programming language now.
I dropped appdemon a year ago, and just removed my last python_script in favor of an automation.
hmm i need to check indeed if I still need the python_script
sometimes python_script is still easier
Wasn't necessary; {{ state_attr('sensor.leafs_game', 'next_game_datetime') - timedelta(minutes=5) }} now works. Thanks for helping me with that modification. Just to be clear, this template trigger should work, shouldn't it?
I seem to remember I used it because of native types,I'll check tomorrow
re-share the full thing please? i don't remember what we were working with
Sure. We added an attribute
called next_game_datetime; that currently result in 2021-01-15 16:55:00-07:00. So, I should be able to use a template trigger of {{ now () == state_attr('sensor.leafs_game', 'next_game_datetime') - timedelta(minutes=5) }} right?
that should work
Oh no, wait a minute that won't does it? Because template triggers only define themselves at boot, not constantly checking, right?
that might have been changed? i don't remember now
worst case you can add a datetime sensor and compare with that
Oh ok. Cool - I hope it did. Thanks!
I tested a couple of different ways and it still didn't work. Any thoughts on why this template didn't render true at the correct time? {{ states('sensor.date_time') == strptime((state_attr('sensor.leafs_game', 'next_game_datetime') - timedelta(minutes=100)), '%p') }}
Hmm
Got it. compare timestamps. {{ as_timestamp(states('sensor.date_time_iso')) == as_timestamp(state_attr('sensor.leafs_game', 'next_game_datetime') - timedelta(minutes=85)) }}
That'll do it
Yep. Thanks a ton. I think I hate times as well now.
https://pastebin.ubuntu.com/p/QzVvD9kK3z/ anybody how to reduce to a single entity?
and i am happy about my lights... ^^
replace the first for with:
{% set item = states.binary_sensor['0x00158d000289ec2d_contact'] %} (as example)
and remove the last {%- endfor %}`
When building a template called x with a template attribute y, is there a way to refer to attribute y inside this template by saying something like self.attribute.y instead of using state_attr('sensor.x', 'y')
yes. states.sensor.x.attributes.y
I don't want to repeat sensor.x though
but this might give errors if the sensor is unavailable, so it's better to use the state_attr() as that can deal with unavailable things
I want it to be inferred. Is it possible?
Also, is it possible to create templates out of entities of an integration in a for loop of some sort? I don't want to repeat all the code for each entity when creating the template when the only thing different between each template is the entity being templated.
you can set a variable to the item and then use that so you only have to define it once
If you want to create template entities, I'm not sure. if you want to create a list of entities for instance for an entity_id to act on, then yes.
Here's what I mean. https://pastebin.ubuntu.com/p/DKqf245mQx/
yahoofinance produces stock entities. I'd like to template each one to customize the icon and the state. I don't want to repeat this huge template for each of these entities. I'd like to apply them to all entities exposed by this integration.
so, yeah you want to create template entities, for which I'm not sure if you can do that with templates. lets wait till the template gods come in 😉
https://pastebin.ubuntu.com/p/mSBgYFTskq/
anyone know what's wrong with these? trying to have sensors based on mqtt messages that take the "time:" field from the sensor and update it whenever "extradata: contact open" mqtt message occurs. i have a bunch of these, but only one updates (guessing it's like the first one triggered or something).
If you want a rounded value of a sensor, is it always necessary to make a dummy sensor?
depends... if you want to show it on a dashboard or graph, I believe you do, but as trigger or condition you could use a template trigger or condition where you react to the rounded value
I just want to show it on my lovelace dashboard.
If you're using the default cards, you'll need to 'wrap' the original with a template sensor. Some custom cards may be able to treat the numbers for you.
Thanks, I will look for one.
If i have a date in (input_datetime.gdate) helper.
And i would like the difference of this date with today in a other helper. (input_number.daysto)
what would be the solution for that?
{{((as_timestamp(input_datetime.gdate) - as_timestamp(now()))/(3600*24))|round()}}
Thanks, Goy yo learn where to put this i think.
probably an #automations-archived when the input_datetime.gdate changes with a service to set the input_number,daysto
I'll try right away 🙂
just a simple list of cast devices, so I've retired the python script as templates can now return proper lists ( to set an input_select) 😉
Anyone know an effective way to strip the start time out of a calendar event so that I can use it in a notification? I want the notification to tell me the start time of the event for the event which is happening tomorrow. Without it including the entire date / time string that gets produced by the 'start_time' attribute.
The end goal is using it as a TTS broadcast at bed time to say "The tesco delivery is at (StartTime) tomorrow"
Found it 😄
{{as_timestamp(states('input_datetime.pre_heat_time')) |timestamp_custom('%H:%M') }}
Thanks Magie 🙂
@thin vine something is wrong. configuration error before i can restart. 🥴
https://pastebin.ubuntu.com/p/MPjJKCc8GM/
Maybe because the gdate is a date and the daysto is a number?
try putting "" around the template
so data: "{{((as_timestamp(input_datetime.gdate) - as_timestamp(now()))/(3600*24))|round()}}"
and don't add 3 accolades { just 2
oh.... sigh
another edit 🙂
data: "{{((as_timestamp(states('input_datetime.gdate')) - as_timestamp(now()))/(3600*24))|round()}}"
you need the states ('') part too 😉
no sure why I missed that part in my first reply 😉
states part ... looking it up
this one
should be good.
I've tested it just with my own input, in the developer tool Template part
{{((as_timestamp(states('input_datetime.pre_heat_time')) - as_timestamp(now()))/(3600*24))|round()}}
that's also a good place to start if you're messing with templates, it gives feedback on what's wrong with your template 😉
so 113 days till holiday 🙂
yep :-)... should be . Thanks a lot (restarting now)
Hello, this is my first discord post ever. I've done a lot of research trying to find a step-by-step tutorial on how to build templates but I'm having zero luck. Tons of examples but not much of the "why". I want to get the status of the lights in my garage (either from a smart plug, luminance sensor, or smart bulb) and have the smart switch control them. I'd like both the sensor and the switch to be one button in Lovelace.
Hi, welcome @long nymph . Not sure why you would need a template for that, maybe I don't understand your question correctly. you can add sensors and buttons directly to lovelace. if you need help with that, #frontend-archived is a better place to ask. Or explain what the template is needed for
Thanks @thin vine. I'd like to combine the output of the sensor/bulb (whether the lights are on or off) to appear on the switch button in Lovelace. The switch is a zigbee mechanical switch that physically toggle the three way switch. It's never synced up correctly!
HI @sudden mango it might but I haven't been able to plug the right info in to make it work. I'm very new to this! To the point that I think all of this gets added to the YAML but I'm not sure...
Alright. Let's see your configuration 🙂
Have you restarted once your changes were made? Switches don't have a reload button besides restart.
I tried to restart but the YAML stopped that!
@long nymph posted a code wall, it is moved here --> https://paste.ubuntu.com/p/RbbKC5m2H9/
The date is not changing.
The yaml code is edited in visual studio and there are red lines under thecode: data: "{{((as_timestamp(states('input_datetime.gdate')) - as_timestamp(now()))/(3600*24))|round()}}"
@long nymph made a few changes.
@sudden mango posted a code wall, it is moved here --> https://paste.ubuntu.com/p/VFKjKC7pbB/
friendly_name has an underscore
and to turn on it wass missing service:
Are you using VS code home assistant addon?
yes. error => Incorrect type. Expected "object"
oh sorry not you i'm not sure on yours
Thanks for the help, I'll give it a try! I was doing it in Developer Tools. I'll take a look at the VS Code addon. I really do want to learn more... is there a "For Dummies" tutorial you recommend?
thats ok 🙂
Honestly just the home assistant documentation websites. Their examples are the bee's knees
most of the time 🙂
does your switch have both turn on and turn off or is it a momentary switch?
OK. I still feel like I missed a few days of class but I'll keep chipping away at it! I appreciate the help @sudden mango and @thin vine
The switch is a normal on and off but the zigbee part fits over the switch and physically moves it
hmm looking into it
you might want the service to be switch.toggle for both or switch.turn_on and switch.turn_off
but the rest looks right to me
it's a 3 way switch in the garage so there is no true on or off. So I went with toggle
@spring zenith you should replace data: with value: see https://www.home-assistant.io/integrations/input_number/ Services part
{% if trigger.to_state.state | float = "on" %}
light.turn_off
{% else %}
light.turn_on
{% endif %}
hmm better:
service: input_number.set_value
data:
entity_id: input_number.target_temp
value: "{{ trigger.payload }}"```
My guess is that this wont work
anyone can help me out
basiclly wanna do one automation for a motionsensor and either turn it off or on depending if the sensor "to" state was on or off 😛
testing 🙂
hmm maby float == "on" ?
@inner gulch the current implementation includes a nice blueprint exactly for that
It does?
I have not updated HA in a while so might be missing somthing 😄
@long nymph For your icons you will also want to change their names to mdi:lightbulb-on-outline and mdi:lightbulb-off. But visual studio code should suggest that for you. If you're unsure of the value_template you should try it in the developer/templates screen
I got 0.114.3 😛
well, you are encouraged to upgrade anyway becuase of security concerns..
Yeah, is just that i need to do alot of work to get it compliant with the newest version 😛
fair enough
things that isnt components anymore but is now integrations
let me dig through my old automations, you should be able to do stuff like you say
trigger:
- platform: state
entity_id: sensor.0x00158d0002b4a1cf_click
to: 'right'
action:
service_template: >
{% if is_state('group.lampen', 'off') %}
script.turn_on_light
{% else %}
script.turn_off_light
{% endif %}```
is what I used to do
so you can adapt from that 🙂
hmm yeah ill see what i do
trigger.to_state is sometimes a bitch to get working as you have no way to check it with the template editor.
I tend to debug that by sending it to notify.webbrowser so I can analyse the syntax of the exact output
getting strange .. Value has now the red lines underneed.
And (like before) i can not execute the annimations
Maybe... browser temp data?
Could it be the '' ... because it is a number ?
Hello all , is it possible to take an mqtt light payload and apply it to an existing light which is not mqtt? for example brightness, color etc.
Currently im extracting and passing individual attributes as follows:
entity_id: light.testlight
service_template: >
light.turn_{{ trigger.payload_json.state }}
data_template:
brightness: '{{ trigger.payload_json.brightness|int }}'
color_temp: '{{ trigger.payload_json.saturation|int }}'
etc... ```
Im basically trying to take an mqtt light remote and have it control a non mqtt light that already integrated with HA. (like a bridge)
alias: 02_Input_Days2
description: ''
trigger:
- platform: sun
event: sunrise
condition: []
action:
- service: input_number.set_value
data:
value: "{{((as_timestamp(input_datetime.gdate) - as_timestamp(now()))/(3600*24))|round()}}"
entity_id: input_number.02_days_to_vacation
mode: single```
should be correct, I don't get errors in vs code
ok.. copy past and.. errors gone?
Looking for that stupid typo of me.
Found it.
Changed the 'Data:' for 'value:' . There was no Data in my code 
I don't see why not rawframe, as long as the trigger data is correct and valid for the light you're sending it to
@thin vine thanks. the trigger data is correct for light control but I dont know how to simplify the data_template (or not use template) to just pass all the json values to the light i want to control. Does anyone know how that might go code-wise? ... so that i dont have to enter brightness, color_temp etc.. all manually
not sure @ivory pawn not to familiar with payload_json
No errors anymore.
But the number is not changing. I executed the automation
@spring zenith currently it only changes on sunrise, that;s what the automation does
trigger: [] .... ofcourse 🙂
https://pastebin.ubuntu.com/p/prDWJnXxDB/
Stil no change..
Can i check logs to see whats happening?
i know
value: "{{((as_timestamp(states('input_datetime.gdate')) - as_timestamp(now()))/(3600*24))|round()}}"
missed the states again... sorry 🙂
alias: 02_Input_Days2
description: ""
trigger:
- platform: state
entity_id: input_datetime.gdate
condition: []
action:
- service: input_number.set_value
data:
value: "{{((as_timestamp(states('input_datetime.gdate')) - as_timestamp(now()))/(3600*24))|round()}}"
entity_id: input_number.02_days_to_vacation
mode: single```
and triggering on changing the input date 😉 not sunset
and yes, I've built it in my HA too, to troubleshoot 😉
Well... just wanted to post that. bacause i tested it in the template tester like you told me.
Im getting smarter after just 3 hours 😂
hehehe
How can i make it so that the data_template (in my example a few above) is ONLY executed if the trigger.payload_json.state == 'ON' ? I just keep getting errors. (I want this because if the state is off then the no data can be passed to a light_turn_off and an automation error is caused)
Done. its working !
I m trying this for 2 weeks in node red. only took me a few hours with your help @thin vine .🤩 Thank you 🙂
Of course not giving up on node red. The mix of it all makes HA perfect 🙂
you could add a condition, as this seem to be an automation? ( as you posted a snippet including action: )
@thin vine hi thanks. it is an automation, with a mqtt trigger, and action as shown. is this wrong?
hi all, i wanna ask i have a couple of automation using the if trigger.entity_id but is there also a trigger.state? so i can do different things depending on the state of the trigger entity?
trigger.to_state.state and trigger.from_state.state are things
ah dammit, i'm just gonna check directly on the state instead. thanks.
states(trigger.entity_id) can also be a thing
i used is_state instead but something clearly didn't work.
🤦♂️ okay i'm back at it's adding a lot of newlines when looking them developer tools, how can prevent that...
i had to do a one line that last automation i did...
{%- -%}
so like this.
https://pastebin.ubuntu.com/p/vMq4b6nM6k/
yep should strip the extra whitespaces
yeah that work phnx where you when i last had this problem 😉 thank you so much
haha
just have to find the other back again and fix it 😄
Holy crap I got my garage light switch button working! Thanks for the help!
nice brig
hello again 🙂
How can I split some variable that are going into my script
here is the start of that script
icon: "mdi:party-popper"
description: 'Set roller shutter to desire position'
fields:
covers_positions:
description: Set which covers are affected and what are positions
example:
- cover.ds_l;60
- cover.ds_s;40
- cover.ds_d;20
- cover.rs_l;0
- cover.rs_d;0
- cover.ss_l;100
- cover.ss_d;100```
so, I want to have one script, which will be handling positions of my roller shutters (covers)..I want something like [key,value] pair
and then to call somehow foreach in action part
and foreach key,value pair to trigger service.set_cover_position
Uh... why not just use scripts the way they're intended and pass in multiple variables when you need to?
🤯
I have a template which uses met.no to get temperature and humidity, I followed a guide to create it, if it wasn't for the guide how would I know what state_attr to use to get the required data?
Developer Tools - States
Thank you
make a template sensor if it reads from existing values @low stream
Nah. You can do it!
I am trying to figure out Home Assistant templates. I have a digital scale that I have hacked with a HX711 and D1 Mini so that I can get the weight of a tank of peroxide.
Thank you Hook UP video for making a propane sensor.
I have set up two helper entities in HA called input_number.peroxide_full and input_number.peroxide_empty. My goal is to use these along with the sensor value from the scale to create a number representing the amount of peroxide available. This will be used to control a meter on my dashboard.
I have been looking at the template docs and believe that is what I need to create. But I am having a hard time getting the concept of how to create one.
I have been experimenting with the template tool but cant figures out how to access the inputs.
Any help would be appreciated.
Thank you
What's the easist way to reject items from a list?
I guess, what's similar to " | random" in that way?
I've tried select and selectattr
I get a weird error "the <generator object select_or_reject at 0x7f90eb75d900>}} is 46 %,
"
{{ state.name | lower | rejectattr("name", "hasp") }} ```attempting with this
('name', 'eq', 'hasp')
Jinja is used by Home Assistant's template engine, see the Jinja Template Designer Documentation
Search that page for built-in tests
can you return the value of a helper to a template?
Same way you return the value of a sensor
@lost rock {{(((states('input_number.scale_input') | int) - (states('input_number.low_value') | int) ) / (states('input_number.high_value')| int) *100) |round(0)}} returns a number between 0 - 100
Thank you
There's probably a prettier way to do that
I have been trying that but it returns error and basically it boils down to the input_number.peroxid_full returning unknown.
what did you set that value to?
I presumed you'd weigh the bottle empty, set the lowvalue manulally, them do the same with a full... scale will them give you a percentage.
I created the helpers in the UI and they work fine in that template.
Thank you @dreamy sinew
Yes in the states tab of the developers tools it it shows a states of 28566.0
@dreamy sinew that didn't work 😄
in the default template editor, I changed weather to sensor and used this: {{ state.name | lower | rejectattr('name', 'eq', "hasp") }}
Hmm
do you see that crazy error?
@lost rock what do you have for the input_number.low_value and high_values?
you can insert numbers there
Yes they are 0 and 30000
Ok, so you can create input_numbers helpers as I did and set their values to 0 and 30000 or hard code thiose in place if what I provided
don't use zero, it'll divide by zero probably.. use 1
ok, show me the template you are using
Is the match test for selectattr not available in HA Jinja?
If not, how would you just return entities that have a certain attribute? Was going to use a regex MAC check.
match is a filter not a test so can't be used that way
Sorry, I don't understand. Why would this not work? {{ states.binary_sensor | selectattr('mac','match','^[0-9A-Fa-f]{8}$') | list }}?
That's not a built in test and HA hasn't implemented it
OK, cool. So easiest to just make some separate groups then of different entities I want to check and expand them. All good 🙂
@lost rock I gave you the template
You just needed to modify it with your entities or values
Just have to use different "low" values for my Wyze sensors than any other battery sensors. The implementation of the WyzeSense API misreports battery levels, so "80%" is actually 0%.
Was gonna identify them by MAC, but will just use separate groups.
You mean like to have 7 scripts for each cover? Or what?
wtf? No. Write one script that accepts an entity ID and a position.
Voila. Infinite combinations possible.
remember this?
i got it. just for something different - at first.
"{{ 'homeassistant/indoor/' + trigger.entity_id.replace( '.', '/' ) | reverse | replace( '_', '/', 1 ) | reverse + '/STATE' }}"
I'm trying to export the data that is displayed under "entities" in configuration. But I cannot find anywhere how to append the "integration" to my list. I'd like to get something like
name, entity_id, integration (kitchen counter light, light.kitchen, Tuya
This gets me the list:
{% for state in states %} {{ state.domain, state.entity_id, state.object_id, state.name, }} {%- endfor -%}
it's just not in the data, so you can't extract it:
<template TemplateState(<state light.staande_lamp=off; min_mireds=153, max_mireds=500, effect_list=['colorloop', 'random'], friendly_name=Staande lamp, supported_features=63 @ 2021-01-17T13:08:56.966935+01:00>)>
This is was I suspected... 😦 It's very sad that the page itself under configuration is not selectable, printable or anything. There must be somewhere where that data is linked since you can filter by "deconz" for example.
it's not available via templates.
Any suggestion elsewhere?
You're trying to display which integration created something? That information is in the entity registry... it's internal only.
you can attempt to backtrack the information in the entity_registry
there have been talks about using the expand method to access device entity_id's but that's about it and no one has stepped up to dev it
So If I want to close all covers, I need to call 7 times same script?
if you know python, you can import json and read core.entity_registry and core.device_registry. Then each item in core.entity_registry.data.entities contains a device_id. Iterate the core.device_registry.data.devices grabbing the id and comparing it to the device_id.
@low flame posted a code wall, it is moved here --> https://paste.ubuntu.com/p/Pj7qvdBJgW/
Actually, what I said isn't even needed. the entity_registry contains the platform.
Yes. That's what I just found
so just iterate the core.entity_registry.data.entities and output entity_id and platform.
Thanks. Off to work on this 😉
have fun
Pasted the content of "core.entity_registry" into https://www.convertjson.com/json-to-html-table.htm and voilà! I have a beautiful table of everything (I'm very low skilled in code)
is there a way to get something like that
payload: "{{ states.TRIGGER.ENTITY_ID.attributes }}"
inside an automation? short version:
[...]
entity_id:
- media_player.livingroom_libreelec
- media_player.bedroom_libreelec
- media_player.guestroom_libreelec
- media_player.XYZroom_libreelec
condition: []
action:
- service: mqtt.publish
data:
topic: "{{ 'homeassistant/' + trigger.entity_id.replace( '.', '/' ) | reverse | replace( '_', '/', 1 ) | reverse + '/STATE' }}"
payload: "{{ states.TRIGGER.ENTITY_ID.attributes }}"
atm i have that block with (for) every media_player (of course each media_player entity once)
i dont know how to insert the variable inside the states string
i think i dont have understood the use of this correctly.
thank you. that helped.
Any tips on how to format an input number? This works {{ '{:02d}'.format(6) }} but this fails to evaluate {{ '{:02d}'.format(states('input_number.day_start_hours')) }}
States are strings. Try casting it to an int/float first.
{{ '{:02d}'.format(states('input_number.day_start_hours') | float) }}
ahh, well that would make sense
Thanks
Although I'm starting to think I'm doing this the hard way...
Thank you. I understand that the problem is that the helper item report unknown so the formula gets a device by 0 error.
set its minimm to 1
Yes I did that. Min is 1 and Max is 30000
{{ states("input_numpger.peroxide_full") }} this should show the value in the result window of the developer tools templates window it doesn't it says that it is unknown. Until I can get that sorted out I am stuck. The formula you sent is correct although I need to account for the tear weight of the empty bottle. The math is not the problem it is getting the data into the formula. I hope that better explains.
I thought that also it makes no difference. same result either way.
you said state tab is correct?
you must be using the wrong name. this works for me: {{ states('input_number.low_value') }}
so, I hope that's a typo... "input_numpger"
Yes it was
Now that is interesting I just got it to work. I went back to the helper and copied the entity id then pasted it into the test block and it is now showing the correct information. don't under stand that one at is is exactly the same. input_number.peroxide_full
thank you for your help I appreciate it.
is there any good documentation on creating the yaml sensor using templates?
this ought to get you started https://www.home-assistant.io/integrations/binary_sensor.template/
but those are only true/false, etc.
easy to start with
I did see that during my journey but could not remember where. thanks for the link I think that will help.
again I appreciate your help. hope I can return the favor sometime.
Those are the official docs, and they are mostly hard to beat, if a bit fragmented
Some time knowing what doc you are looking for is the issue for me. 😄
LOL I can never find the right term to search for
Yep!! any way here you gol
{% set full=states('input_number.peroxide_full') | float %}
{% set empty=states('input_number.peroxide_empty') | float %}
{% set raw=states('sensor.peroxidescale_hx711_weightraw') | float %}
{% set level = ((raw - empty)/(full - empty)) * 100 %}
{{level}}
works fine it is returning 74 at this time.
Now to create the sensor so it can be used in lovelace.
Hey all, I am trying to show a history graph with humidity and heating/cooling actions from my thermostat. When I add "climate.thermostat" to my history card, it shows on the graph when it is heating/cooling. How can I do this myself? I tried making a template with the hvac_action attribute, and adding it to my history graph, but that does not seem to work as I want it to
You can't do it yourself, it's only available on climate devices
Darn, thanks for the info
Hello, some help pls? - I do not want brightness to be allowed to be 0 but am struggling with the code in my automation
data:
# brightness: '{{ trigger.payload_json.brightness|int }}'
brightness: >
{% if '{{ trigger.payload_json.brightness|int }}' > 0 %}
'{{ trigger.payload_json.brightness|int }}'
{% else %}
'1'
{% endif %}
removing the quotes doesnt work either
why are you templating inside of your template
What would be the better way? should i use data_template?
does the editor work when the payload is from mqtt (json payload) ?
I have never used the UI, I don't really know
{{ trigger.payload_json.brightness if trigger.payload_json.brightness > 0 else 1 }}
@lost rock posted a code wall, it is moved here --> https://paste.ubuntu.com/p/pF9FsFZ8WM/
{% set trigger = {
"payload_json": {
"brightness": 2
}
} %}
{{ trigger.payload_json.brightness if trigger.payload_json.brightness > 0 else 1 }}
Do stuff like this to test
{{ [trigger.payload_json.brightness | float, 1] | max }}
😉
You'll want to cast to a number type before performing comparisons.
And by the time you do that twice in Bu's original template, you end up with quite an unwieldy mess 🤣
the json is parsed as a number
Pfft. Maybe.
for suresey, lol
I still prefer mine 😉
I like mine 😛
Readability... 'pick the bigger of these two (or more) numbers'
@thorny snow Just wanted to let you know the final sensor is working find. Thanks again. I tried to past in the final yaml clip but the Has Bot moved it and provided a link. Not sure what that was but it is working.
thanks @lost rock and @timid osprey ill try it out all out and report back 🙂
I hate the 'x if a else y' syntax Jinja has going on. It's not very newbie friendly... you have to skip ahead to parse the middle section before you think about which direction to look for the outcomes.
mine literally reads left to right
You can read it in whichever order you want. That's not the order in which the logic is defined though.
Or rather, not the order in which it's performed.
you focus on how humans read it, not the machines
Eh... I don't 😄
💋
JavaScript's ternary operator is great. a ? x : y means the same as Jinja's weird-ass syntax but it reads in order.
'If a is true, do x, else y'. Way more logical.
"jinjas weird ass syntax" is actually python
Fine, I'll redirect my ire at Python 😄
I'll take the | max over ternary any day. It's more succinct and it's expansible for when you have more than 2 items to compare.
PERFECT!!! and easy to understand ... (changed float to int and all is good) THANKS @ivory delta 🙂 👍 💯
See... my option's better. It's official 🤣
lmao
1 out of 1 users would recommend.
copy/paste, EXCELLENT
| floating an int
EXCELLENT
just catching those string edge-cases, I see
Nah... there's so many ways you could achieve the same thing. If it works, it works. I just try to write things in a way that I know I'll understand when I see them again in 6 months and are easy to maintain.
Yeah, defensive coding. Assume it could be any type but force it into the type you want 😄
how many ways to skin a cat
{{ [trigger.to_state.state | float, 1] | max }}
Bingo
Do that with your version 😄
300 lines later...
wut
Kidding 🙂 Love you
I knew you were kidding but I couldn't figure out what .state was, lol
my HA configs are quite simple compared to everyone I seem to try to help, 😛
I rely on other peoples problems to learn more about HA
Nothing wrong with that. I spent my first few months on this server lurking and learning from other people's problems too.
There's still so much I don't know but I'm pretty confident with the bits I understand now.
the jinja well is deep
Hi , maybe someone could help me on getting a attribute value
I want to get the name of face detected in Image detection DLIB
by using the template : image_processing.dlib_face
in the template , i use - '{{ states.image_processing.dlib_face_dashboard }}'
and get a output of :
<template TemplateState(<state image_processing.dlib_face_dashboard=1; faces=[{'name': 'Mig', 'entity_id': 'image_processing.dlib_face_dashboard'}], total_faces=1, friendly_name=Dlib Face dashboard, device_class=face @ 2021-01-17T18:57:58.696476+00:00>)>
How can I get just the 'name' ?
in this case = Mig
Did you check the documentation?
state_attr('device_tracker.paulus', 'battery') will return the value of the attribute or None if it doesn’t exist.
state_attr('image_processing.dlib_face_dashboard', 'name')
like this ?
Iscrmbling arround this and read the isntructions but I'm not able to get it
Is it possible to have a Template Sensor that doesn't convert to text, having to do something like this, makes me think I missed something in the docs {{ ((strptime(states('sensor.calculated_system_start_time'), '%H:%M:%S')) - timedelta(minutes=15)).time()}}
That doesn't convert to text? All states are strings, if that's what you're hoping to avoid.
Was afraid of that
If you're depending on using it as another data type, deal with the types after you read from the state.
Worth noting that a lot of (but certainly not all) integrations can auto-cast data types as needed.
Was trying to save time, sensor.calculated_system_start_time is a template sensor
where I do some datetime math and then output it as a datetime.time
so just seemed like a pain to have to convert back to datetime then to string to use in an automation
Thanks for the clarification
@ivory delta it doesnt display the name
{{state_attr('image_processing.dlib_face_dashboard', 'faces')}}
displays :
[
{
"name": "Mig",
"entity_id": "image_processing.dlib_face_dashboard"
}
]
is it always one item or could there be multiple?
if there are multiple do you want all of them or just the first one?
{{ ', '.join(state_attr('image_processing.dlib_face_dashboard', 'faces')|map(attribute='name')|list) }}
or remove the join bit if you just want the raw list
... this is a face detection , I want to have a wall tablet display a diferent lovelace view for diferent users
above would output "name1, name2" vs ["name1", "name2"]
i will add this to a automation, so when someone is in front of the tablet, it will show his lovelace view
so i will probably use without join and work the automation for the result of template
we are just 4 persons here , and maybe any other unknown face (guests)
just this then:
{{ state_attr('image_processing.dlib_face_dashboard', 'faces')|map(attribute='name')|list }}
which is expected
yes , but woudnt just the name Mig , be more easy for the autmoations ?
you said you want to handle multiples
yes
if multiples are an option you need to have your response be consistent
but just one at a time
that's not how this works
? there will be just one person facing the tablet ..
else will take care of non positive identifications
you misunderstood the question i was asking earlier
{{ state_attr('image_processing.dlib_face_dashboard', 'faces')|map(attribute='name')|first }} will get you there
but if the camera ever pulls up more than one person at once you'll only ever get the first one in the list
it worked
I now get the point on your question
.. yes .. if more than 1 person , it will just display First
.. and yes , I will need to think on how to display for when more than one identifiaction is detected
.. thank you so much @dreamy sinew - will get to work with this lovelace touchless panel 😉
hi. i'm trying to put personal values from sensors of humidity and temp intto this template, but seems i cannot find correct syntax. help needed 🙂
hi, is something like this not possible?
{% set entity_id = 'sz_light' %}
{% set lights = ['group.{{entity_id}} '] %}
{{ lights }}
i want to get group.sz_light as output
you should not write {{ }}in {% %}
{% set entity_id = 'sz_light' %}
{% set lights = ["group."~entity_id] %}
{{ lights }}
how do i have to do this in a state check?
{% if is_state('input_boolean.lighting_"~entity_id', 'on') %}
{{ states('input_boolean.lighting_"~entity_id') }}
wont work too i get unknown as output here.
What are you trying to accomplish?
this is the whole template
entity_id: |
{% set lights = ['group."~trigger.entity_id'] %}
{% if is_state('input_boolean.lighting_"~trigger.entity_id', 'on') %}
{{ expand(lights)|selectattr('state','eq','on')|map(attribute='entity_id')|join(',') }}
{% else %}
{% endif %}
i've never seen ~trigger before
this is part of an automation
i want to use trigger.entity id
nontheless it wont work if i just use entity_id in the template editor without trigger
this here wont work:
{% set entity_id = 'sz_light' %}
{% if is_state('input_boolean.lighting_"~entity_id', 'on') %}
{{ entity_id }}
{% else %}
{% endif %}
input_boolean.lighting_sz_light is configured and is state on off course
I have never seen ~ used in a template
mh okay, is there a another way to accomplish this?
as ~ only works in expressions?
The snippet slashback shared appears to work just fine.
If yours doesn't work, you're doing something wrong.
The random double quote you've added won't help, nor will the fact you're trying to use an expression inside quotes.
I'm trying to extract the counter attribute from the trigger payload for my hue dimmer switch via MQTT integration
I've managed to find that the counter is included in the variable {{ trigger.to_state }} but the value of that looks like this:
<state sensor.lounge_dimmer_action=up-press; action=up-press, brightness=255, counter=1, duration=0, linkquality=78, update=state=idle, update_available=False, friendly_name=Lounge Dimmer action, icon=mdi:gesture-double-tap @ 2021-01-18T03:12:05.004430+00:00>
Is there inbuilt templating to work with that format, or am I going to have to figure something else out?
Copy this to the template editor and see if it will change with different button presses {{ state_attr('sensor.lounge_dimmer_action', 'action') }}
Or maybe just just the state of the sensor
just found it actually - trigger.to_state.attributes.counter
Working Automation
- alias: Dimmer - Bedroom (up-press)
trigger:
- platform: state
entity_id: sensor.bedroom_dimmer_action
to: up-press
action:
- service: light.turn_on
data:
brightness: '{{ (states.light.bedroom_light.attributes.brightness + trigger.to_state.attributes.counter * 255 / 10) | int }}'
entity_id: light.bedroom_light
only got my zigbee2mqtt running this weekend, so only just getting to learn all the pieces that make things move - prior to that I was just integrating with hue bridge which was 🚮
just found the template editor - that got me over the last hurdle
is there any reason lots of ppl here use state_attr instead of dot notation?
Avoid using states.sensor.temperature.state, instead use states('sensor.temperature'). It is strongly advised to use the states(), is_state(), state_attr() and is_state_attr() as much as possible, to avoid errors and error message when the entity isn’t ready yet (e.g., during Home Assistant startup).
yup - just found that in your link, thanks
ehh trigger.<to/from>_state.attributes is fine enough
assuming you don't completely fubar your trigger
Just a guess but seems like the action attribute would actually provide the correct state
technically I'm also loading the light state
coming from a heavy .net background - dot notation feels far more natural - I'll keep an eye on the error log and see if it becomes a problem
oh, yeah might as well play it safe for that one
using the object notation will raise exceptions if the thing you're looking for doesn't exist
I mean, if the light hasn't loaded/initialized yet - then the automation isn't going to work anyways - so having a log of why it failed could come in useful
it doesn't give you the why, just a big nasty exception
yup - but silent failure is worse 😂
Where as the other way you get a none doesn’t exist type error I think
ah - may be more useful then
vs state_attr() which handles the problem and you can handle the return with defaults
With the help of some fine people i got something working.
And today... it does not work any more?
made automations.yaml file empty. Pasted the previously working code in . so now i have only 1 automation.
An its not working anymore? 😖
It's for concatenation
the snippet works fine yes. but i want to dynamically check the input boolean as showed in my last example. i cant get that to work.
The last exampl you past has an issue with the quotes as mono explained. The correct version:
{% set entity_id = 'sz_light' %}
{% if is_state('input_boolean.lighting_'~entity_id, 'on') %}
{{ entity_id }}
{% else %}
{% endif %}
Same issue with your previous code. Try fixing the quotes
What I don't understand is this is_state('input_boolean.lighting_'~trigger.entity_id, 'on') --> trigger.entity_idwill be something like domain.entity, so input_boolean.lighting_domain.entity will not be a valid entity id
I guess what you want is to remove the domain part before concatenation. Like so:
is_state('input_boolean.lighting_'~trigger.entity_id.split('.')[1], 'on')
how would i write a template so that a "wait for trigger" action goes off 30 mins before the time in a time input helper?
i have never used templates before
not sure this is the most efficient way but this should work : {{as_timestamp(now()) + 30*60 >= as_timestamp(states('input_datetime.your_entity')) }}
thanks
https://pastebin.ubuntu.com/p/jS2SbmJvKz/ how can i put my sensors in this macro ?
this is not valid % set t = 7.5*{{state '(sensor.immax_temperature)'}}/(237.7+{{state '(sensor.immax_temperature)'}}) %}
You should not write {{}} within {% %}
and the quotes are wrong
{% set t = 7.5* (states('sensor.immax_temperature') | float)/(237.7+(states('sensor.immax_temperature')| float)) %}
ty
& {% set e= 6.112 * et * ({{state '(sensor.immax_humidity)'}}/100) %} should be {% set e= 6.112 * et * ((states('sensor.immax_humidity')|float)/100) %}
is working. now i can integrate in a template sensor with macro as value ?
yes, you put your macro in the value_template of your sensor
though why are you using a macro here?
why don't just put
value_template: >
{% set T = 2 %}
{% set H = 45 %}
{% set t = 7.5* (states('sensor.immax_temperature') | float)/(237.7+(states('sensor.immax_temperature')| float)) %}
{% set et = 10**t %}
{% set e= 6.112 * et * ((states('sensor.immax_humidity')|float)/100) %}
{% set humidex = T+(5/9)*(e-10) %}
{% if humidex < T %}
{% set humidex = T %}
{% endif %}
{{humidex}}
because i am dumb? :))
h = humidity?
since you get if from the sensor now, you don't use it in your macro, nor it is needed to define it as avariable
i see. indeed i have this smart guy called immax that has temp humidity and lux measurements
i guess I can eliminate T and H
You can make it clearer
value_template: >
{% set temp = states('sensor.immax_temperature') | float %}
{% set humid = states('sensor.immax_humidity') | float %}
{% set t = 7.5*temp/(237.7+temp) %}
{% set et = 10**t %}
{% set e = 6.112 * et * humid / 100 %}
{% set humidex = temp +(5/9)*(e-10) %}
{% if humidex < temp %}
{% set humidex = temp %}
{% endif %}
{{humidex}}
Or
value_template: >
{% set temp = states('sensor.immax_temperature') | float %}
{% set humid = states('sensor.immax_humidity') | float %}
{% set t = 7.5*temp/(237.7+temp) %}
{% set et = 10**t %}
{% set e= 6.112 * et * humid / 100 %}
{% set humidex = temp +(5/9)*(e-10) %}
{{ [humidex, temp] | max }}
even nicer
when u know syntax...things are so simple
to have only digit number i put {{ [humidex, temp] | max | float }} ?
uh..doesn't work
you mean to round it ?
yup. now i have 23.66250298780825
| round
pf..told u i am du... :))
🙂
when defining sensors in the configuration.yaml it starts with these 3 lines
sensor:
- platform: template
sensors:
does sensor: have to be a unique name to each sensor?
as im running in to issues when adding a second template which is killing the one before it
where can you find the template code used to build the states card? I want to make a markdown template showing the attributes for a specific sensor in a similiar way
There's multiple ways you can add more template sensors:
sensor:
- platform: template
sensors:
a:
...
- platform: template
sensors:
b:
...
or
sensor:
- platform: template
sensors:
a:
...
b:
...
or
sensor:
- platform: template
sensors:
a:
...
sensor b:
- platform: template
sensors:
b:
...
you'll have to be specific
i.e. maybe supply a picture of what you're talking about
just print out the contents in yaml
dont want to bother with formatting, a nice indented list will do
https://1drv.ms/u/s!AuIVw8SdOxQOiPI-MDF8dzVQaOAJLQ?e=5sJrqx something like this
Yeah, that's not a simple template. You'd need to show the object you intend to format with yaml. The template would most likely be one of the harder templates to come up with as it would require recursion with a macro.
hehe, yeah I was hoping to steal it from the github source 🙂
it's written in python, so its not transferable
aah, I see. i thought it uses templating internally aswell
yeah, ideally this could be a custom card for everyone to use
so who's going to develop it?
just drop it in a view for those couple sensors you use for housekeeping or other interesting stuff 🙂
my knowledge of python is rudimentary, but if there is interest why not
so far I've written a couple of small tools for MQTT stuff mostly
but I imagine they have access to those elements that render the entity in developer tools
that depends if it was made generic or not
how do i print attributes as json for my payload?
payload: "{ \"state\": \"{{ trigger.to_state.state }}\", \"attributes\": {{ trigger.to_state.attributes }} }"
results in
{ "state": "idle", "attributes": {'friendly_name': 'LibreELEC Livingroom', 'supported_features': 186303} }
but should look like this:
{ "state": "idle", "attributes": { "friendly_name": "LibreELEC Livingroom", "supported_features": "186303" } }
e.g.
{
"state": "idle",
"attributes": {
"friendly_name": "LibreELEC Livingroom",
"supported_features": 186303
}
}
i tryed the to_json - ( {{ trigger.to_state.attributes | to_json }} ) which does not work at all Object of type mappingproxy is not JSON serializable
i think this belong here. not to automation.
posted that accidentally in the wrong channel
i have read the https://www.home-assistant.io/docs/configuration/templating/#tofrom-json-examples
but i think i dont understand them
i have tried
payload_template: >
{% set payload_data = "{{ trigger.to_state.attributes | to_json }}" %}
# stringified object: {{ payload }}
# object|to_json: {{ payload |to_json }}
payload: "{{ payload_data }}"
the error was two or more values in the same group of exclusion 'payload' @ data[<payload>]
If I understand the message, it says you can't set a payload && payload_template at the same time, you have to return payload_data in payload_template
well. that with the int is nice to know.
so i can simply parse them like every json "key": "value" or "key": int
but how do i get the attributes into json format?
oh. sure. i will try. 🤦
payload_template: >
{% set payload = "{{ trigger.to_state.attributes | to_json }}" %}
will set an empty payload
you have to return something
you shoud write payload_template: "{{ trigger.to_state.attributes | to_json }}"
i also tried an {{ trigger.to_state.attributes | replace( '\'', '\"' ) }} with no success. Error loading /etc/homeassistant/configuration.yaml: while scanning a double-quoted scalar
nope...
Object of type mappingproxy is not JSON serializable
GOT IT!
ATM i donno why
payload: >
{ "state": "{{ trigger.to_state.state }}", "attributes": {{ trigger.to_state.attributes | replace( '\'', '"' ) }} }
{
"state": "off",
"attributes": {
"friendly_name": "LibreELEC Livingroom",
"supported_features": 186303
}
}
kind of...
that media_position_updated_at and the is_volume_muted crashes my json.
{ "state": "playing", "attributes": {"volume_level": 0.66, "is_volume_muted": False, "media_content_type": "video", "media_duration": 3523, "media_position": 1169, "media_position_updated_at": datetime.datetime(2021, 1, 18, 15, 36, 13, 727521, tzinfo=datetime.timezone.utc), "media_title": "Test Video", "media_album_name": "", "media_series_title": "", "media_season": -1, "media_episode": -1, "friendly_name": "LibreELEC Livingroom", "entity_picture": "/api/media_player_proxy/media_player.livingroom_libreelec?token=XX&cache=XX", "supported_features": 186303} }
i need a different approach
@subtle shore posted a code wall, it is moved here --> https://paste.ubuntu.com/p/KxpvS8Sftd/
yeah. i thought the same...
is there no better way?
I need to divide a value by 3600 to get the proper sensor value. Any ideas? I found some reference to multiplying instead {{ value | multiply(1/3600) | float(2) }}
I guess that's the best way?
Err sorry, opposite : 3600 / value is what I need to do. In any case, that gave an error as value is maybe a string?
Maybe I can cast it to float first to keep it more readable.. eg value_template: "{{ ((3600 / (value | float)) | float(2) }}"
Invalid config for [sensor.mqtt]: invalid template (TemplateSyntaxError: unexpected '}', expected ')') for dictionary value @ data['value_template']. Got '{{ ((3600 / (value | float)) | float(2) }}'. (See ?, line ?).
Too many brackets 🙂
https://i.imgur.com/xM32T4R.png Any ideas how to get the # of digits down? I thought float(2) would give me 2 decimals
value_template: "( ((3600 / ( {{ value }} | float ) | float(2) )"
should it not look like this?
Doesn't that work ?`
payload: >
{{ { "state": trigger.to_state.state, "attributes": trigger.to_state.attributes} }}
?
sry. i just startet with templating.
When configuring a value_template and the json output has a weird character in it, what's the proper way to escape the template so it will parse properly? Example:
- platform: mqtt
name: "Roxy - Position Event"
state_topic: "AutoPi/event.vehicle.position"
value_template: "{{ value_json.@tag }}"
no. it returned
{'state': 'paused', 'attributes': mappingproxy({'volume_level': 0.66, 'is_volume_muted': False, 'media_content_type': 'video'[...]
Here's what did it : value_template: "{{ '%.2f'%(3600 / (value | float)) | float }}"
will the ascii code work as Hex? eg %40 for @
Have not tried that yet. Worth a shot I suppose
that is an output string literal as opposed to part of a variable name, but also worth a try, yeah.
\x40 would be an @ in this example
yep. Just tried that -- configuration checker is not happy with that.
nor does it like %40
Strange.
And something like this:
{% set str = '{ "state": "'~trigger.to_state.state~'", "attributes": {' %}
{% set ns = namespace(str=str) %}
{% for attr in trigger.to_state.attributes %}
{%set ns.str = ns.str~'"'~attr~'": "'~trigger.to_state.attributes[attr]~'",' %}
{%endfor%}
{% set ns.str = ns.str[:-1]~"}}" %}
{{ns.str | from_json}}
``` ?
if u use ' inside the of " you could do that what i just discovered:
Try |urlencode at the end
- platform: mqtt
name: "Roxy - Position Event"
state_topic: "AutoPi/event.vehicle.position"
value_template: >
{{ value_json.'\x40'tag }}
Invalid config for [sensor.mqtt]: invalid template (TemplateSyntaxError: unexpected char '@' at 14) for dictionary value @ data['value_template']. Got '{{ value_json.@tag | urlencode }}'. (See ?, line ?).
Ahh ok I see the problem
it has to do with the python variable name
value_json.get('@tag')
as payload_template?
found character '%' that cannot start any token```
and if that works. looks like magic. 😄
in payload
still the same.
payload: >
{% set str = '{ "state": "'~trigger.to_state.state~'", "attributes": {' %}
...
strange...
damn. missed that > -.-"
{'state': 'paused', 'attributes': {'volume_level': '0.66', 'is_volume_muted': 'False', 'media_content_type': 'video', 'media_duration': '3523', 'media_position': '1308', 'media_position_updated_at': '2021-01-18 16:35:28.771510+00:00', 'media_title': Test Video': '', 'media_series_title': '', 'media_season': '-1', 'media_episode': '-1', 'friendly_name': 'LibreELEC Livingroom', 'entity_picture': '/api/media_player_proxy/media_player.livingroom_libreelec?token=XXX&cache=XXX', 'supported_features': '186303'}}
@dreamy sinew thanks, get('@tag') worked!
i think im happy with my solution.
it will work for me.
thank you very much.
its not pretty but its mine. 😛
should the attributes not already be in json foram?
if not:
maybe there will be a simpler way in the future.
something like trigger.to_state_json.attributes or something?
as feature request maybe?
i'm looking for some dealing with filtering items out of a list. based on some forum comments, there currently aren't filters defined which will make this easy but... well who knows.
So, here's a list of lights by entity name: {% set lights = states.light | map(attribute='entity_id') | list %}
and when i do a {{lights}}, cool there's my list
what i'd like to do is to remove items from that list matching a certain string
use | exclude
Ah, is that a HA addition?
btw: last line modification
{{ ns.str | from_json | replace( '\'', '"') }}
trying to find docs on that...
TemplateAssertionError: no filter named 'exclude'
not coming up with much - any idea where i can find docs on how to use exclude? even an example would do
It is actually reject, not exclude... my bad. too many programming languages, everybody does things differenty. ```
{% set lights = states.light | map(attribute='entity_id') | list |reject("equalto", "light.family_room_lights")|list %}
{{ lights }}
if you want to use wild cards, you may have to use regex...
Which I don't think you can use in reject iirc
i will for sure have to use some sort of wildcard/regex, as i will not know ahead of time the full name of the element(s) in the list i want to remove
is there a list of supported filters and tests?
The default set from jinja2 plus any the HA template docs talk about
Jinja is used by Home Assistant's template engine, see the Jinja Template Designer Documentation
Search "built-in filters"
roger that. so i see reject there, i think my problem is the there are no built-in tests that can do substring or regex
Yep that's the main issue. The regex stuff that was added in HA are filters and not tests so you can't combine that way
But they might work on their own
not getting anywhere there. thinking a for loop might be my solution.
Might be unfortunately
which i guess brings me to my next problem - can i concatenate a list?
goal - create an empty list foo, iterate through my list of lights in a for loop, run my regex test on each element, if it matches, add it to foo
Yes but no
maybe make a big string, with comma separation and do a join afterwards?
isn't that all a list is anyway, with [] on the outside?
hey @thorny snow long time my friend!
hey 🙂
{% set ns = namespace(l1=[]) %}
{% for item in list if 'foo' in item %}
{% set ns.l1 = ns.l1 + [item] %}
{% endfor %}
{{ ns.l1 }}
something like that works @fossil totem
but you have to use a namespace and you have to recreate the list each time like that
{% set filtered_lights = "" %}
{%- for light_entity in states.light | map(attribute='entity_id') | list -%}
{% if light_entity | regex_search("light.hasp_.*selected_.*ground_color") %}
{%- else -%}
caught {{light_entity}}
{% set filtered_lights = filtered_lights + "," + light_entity -%}
{%- endif -%}
{%- endfor -%}
that will fail for namespacing reasons
things inside the for loop can't touch things outside the loop
ahhhh that's why i'm not able to concatenate. mystery solved scoob!
yup. hence my un-helpful "yes but no" answer
i just had to switch to my laptop because i wasn't going to show my example typed out on mobile
LOL I think I was the one looking for the exclude filter and HASPs
namespacing is a good hack to get you around a few things but its definitely cumbersome
https://www.home-assistant.io/docs/configuration/templating/ mentions relative_time but when I try to use it, I get TemplateAssertionError: no filter named 'relative_time'
I guess I use it wrong?
Did you pipe a date time object?
how do I verify that before? as_timestamp work on it fine
{{ check.last_ping|as_timestamp }} =1610991122.0
{{ check.last_ping|relative_time }} = TemplateAssertionError: no filter named 'relative_time'
i don't think its a filter, its probably a global
try relative_time(check.last_ping)
yeah already did, it just returns the datetime obj
maybe if I format that one to a timestamp before...
hmm, then it retuns the timestamp
{%- set lights = namespace(light=[]) -%}
{%- for light in states.light | map(attribute='entity_id') | list -%}
{%- if light | regex_search("light.hasp_.*selected_.*ground_color") -%}
{%- else -%}
{%- set lights.light = lights.light + [light] -%}
{%- endif -%}
{%- endfor -%}
{{lights.light}}
it works!
also is the bot complaining about too many lines there or something?
The bot doesn't like jinja.
i'll play my watermelon card to defeat the bots X
ahh, I see now phnx how some of these are filters and some aren't
https://github.com/home-assistant/core/pull/42338 seems there was issues of some sensors using relative_time in their attributes, causing constant updates
maybe it was disabled globally?
no, I just used it
@charred dagger that's... unexpected. are we not meant to use jinja or somesuch?
It's just saying that's not valid yaml syntax. Which it isn't.
the library discord uses for syntax highlighting doesn't have jinja
only like django and random other things
allright, just want to make sure i'm not being a bad chatter etc
anyway @dreamy sinew you are a wizard my friend and i sure appreciate the input
odt, can you give me the exact state of your check.last_ping and I'll try to make 'er work for ya
check.last_ping 2021-01-18T01:03:55+00:00
thanks
well, thank you 🙂
really weird it doesnt do anything for me
its such an old timestmap, cant be any timezone weirdness
default behavior for most things that were added from HA is to return what it got sent if whatever it tries to do fails
that's what relative_time() wants to do
yeah, it is fun because as_timestamp has magic that makes it work I guess if it is a string 😛
forgiving_as_timestamp
she forgiving
I am using strptime to try and get it for you
yeah
if you want to toy with that, that is what I was doing
but might be easier to make it unix before parsing, lol
hmm, i made my node red http request return a json object instead of a string but that just breaks the entire attribute
(there is json to yaml conversion before the sensor is created)
last_ping: '2021-01-18T18:02:02+00:00' pretty sure it's the best Node Red can do
startAt: '2022-01-27T20:00:00.000Z' would be a proper datetime obj I guess
so its an issue with the API I use to get it from
I am doing something wrong, lol
might aswell do the conversion in node red, it has moment.js
i'm a fan of moment
plus makes it easier on the frontend
I used to use it but it was just massive and I like date-fns a lot more now
{{ strptime("2021-01-18T01:03:55+00:00", "%Y-%m-%dT%H:%M") }} not sure what I am overlooking 😛
no worky
you gotta account for the tz
okay, uno momento
hrmm, I don't see one for TS that have :
I thought it would at least give me something even though I didn't do the z yet
nope because the format you're defining doesn't match the string you're sending
ahh, I just was hoping it would return the bits that did match
I tried to strip the z jjust as a test and still wonky
oh, I am blind as usual
"%Y-%m-%dT%H:%M%z"
lol
I was missing a : but you are too, lol
{% set time_sz = "2021-01-17T01:03:55+00:00" %}
{{ relative_time(strptime(time_sz, "%Y-%m-%dT%H:%M:%S%z")) }}
oh i just copy-pasted what you had
@deft night DID IT
YEAH< THAT IS THE PROBLEM
I AM BLIND
😛 ❤️
my
debugger is on the fritz
lol
no problem. I wanted to learn that now so i didn't deal with it later
I imagine HA will eventually expose some of the internal date functions they have eventually
or just some of the native ones
https://1drv.ms/u/s!AuIVw8SdOxQOiPJA77BMV9wmS70j5g?e=i7IIbX just playing around with attributes a bit, ended up replicating the whole healthchecks.io checks API
thanks again! now I can leave it for another time how to figure out how to append a new object into an array using jsonata
Need a 2nd set of eyes on this one please:
- platform: template
sensors:
radiant_energy_cost:
value_template: {{ ((states('sensor.radiant_kwh_raw_data') | float * 0.13)) | round(2) }}
friendly_name: 'Radiant Cost Today'
unit_of_measurement: "$"
Error is:
Error loading /config/configuration.yaml: invalid key: "OrderedDict([("((states('sensor.radiant_kwh_raw_data') | float * 0.13)) | round(2)", None)])"
in "/config/configuration.yaml", line 1906, column 0
Oddly, if I put a $ sign before {{, it evaluates properly
but that makes it a string, and my graphs won't accept a string
you need "" around your value_template
Hey guys, hope you can help. I'm building a script that uses an input_select. Based on the value of input_select I'd like to start one automation or another. No issues here, however: Both services need different attributes to be set, I can't get this to work with templates.
Meaning: I can set a value to a specific attribute but one service needs different service data than another. If I specify too much service data the service wont work
For example, see this code:
- service: media_player.play_media
data_template:
entity_id: >
{% if is_state("input_select.chromecast_radio", "Kitchen") %}media_player.kitchen
{% elif is_state("input_select.chromecast_radio", "Everywhere") %}media_player.home_group
{% endif %}
media_content_type: 'audio/mp4'
I'd only like to specify media_content_type if "input_select.radio_station" is not Spotify. If it's Spotify I shouldn't send media_content_type because the service spotcast.start doesn't accept it
Hope you can point me in the right direction. I saw a solution another based on automations, but I don't want to immediately start something on a change of the input_select
just do another if/elif/endif in media_content_type based on the input_select.radio_station like you did for the entity_id
But won't that still send media_content_type itself?
@brisk temple thanks - I swear I tried that - but it works now - thanks
If I try to call the service in Developer Tools, I get an error stating extra keys are not allowed. Testing this:
entity_id: media_player.kitchen
media_content_type: ''
uri: "spotify:playlist:29aiPfdrGUh6TDEjvsJV3r"
Because media_content_type is not accepted for the service spotcast.start
are those options hard-coded?
for each?
{% set service_data = {'spotify': {'entity_id': 'media_player.kitchen', 'uri': 'spotify:playlist:29aiPfdrGUh6TDEjvsJV3r'}, 'input2': {}} %}
{{ service_data[states('input_select.radio_station')] }}
oh, you're using 2
probably need to stack a few things but could make it work
maybe even make a macro
I have lots of sensors in my configuration.yaml, how do I split them out to make it tidier?
You'd ask in #integrations-archived
Thanks phnx, didn't know about service_data. I'll take a look around your suggestion, sounds like it could work 🙂
Thanks for helping along!
Figured as much, sorry don't understand the concept so much yet..
Need to figure out how to use variables in setting these states, but I'll Google my way around first 🙂
"{{ service_data[states('input_select.radio_station')] }" just lists all the stuff I've set in the previous line right? To dynamically assign the required service attributes?
you set keys in that dict for each input value. that will return the payload for that input value
Thanks again 🙂
Yeah, now trying to figure out to set a variabele based on one input select to include in the mentioned service_data dict
{% set location_map = {'Kitchen': 'media_player.kitchen', 'Everywhere': 'media_player.home_group'} %}
{% set entity = location_map.get(states('input_select.chromecast_radio'), 'media_player.YOURDEFAULT') %}
{% set service_data = {'spotify': {'entity_id': entity, 'uri': 'spotify:playlist:29aiPfdrGUh6TDEjvsJV3r'}, 'input2': {'entity_id': entity}} %}
{{ service_data[states('input_select.radio_station')] }}
Wow
for a total of:
- service: media_player.play_media
data_template: >-
{%- set location_map = {'Kitchen': 'media_player.kitchen', 'Everywhere': 'media_player.home_group'} -%}
{%- set entity = location_map.get(states('input_select.chromecast_radio'), 'media_player.YOURDEFAULT') -%}
{%- set service_data = {'spotify': {'entity_id': entity, 'uri': 'spotify:playlist:29aiPfdrGUh6TDEjvsJV3r'}, 'input2': {'entity_id': entity}} -%}
{{ service_data[states('input_select.radio_station')] }}
meh, my spacing is off
No worries, this is a huge help already
Also not looking for copy/paste answers, this is more than I could wish for
Ouch
Perfect, I understand the code @dreamy sinew, will adapt it to match my situation. Thanks for giving me some insight and learning me some new approaches
np these challenges can be fun
How would I take energy in kwh, then times it by my unit price to give me a visual representation of cost?
Perhaps I do need some more help 🐵
@modest sparrow posted a code wall, it is moved here --> https://paste.ubuntu.com/p/nd9rMXPTfC/
Giving me the following two errors, but I cant figure out why:
Invalid config for [script]: [data_template] is an invalid option for [script]. Check: script->data_template. (See /config/configuration.yaml, line 15).
Invalid config for [script]: expected dict for dictionary value @ data['sequence'][1]['data_template']. Got None extra keys not allowed @ data['sequence'][1]['mode']. Got None. (See /config/configuration.yaml, line 15).
Would you mind to take another look @dreamy sinew ?
Brought it down to this: https://pastebin.com/6kiAx9hS Now I only get the error "Invalid config for [script]: expected dict for dictionary value @ data['sequence'][1]['data_template']. Got None"
I think the error is in "{{ service_data[states('input_select.radio_station')] }}" but I've selected a proper value (Spotify in this case). Also if I use "{{ service_data[states(music_type)] }}" (which I want to do because I want to set it dynamically) I get the same result
@north acorn posted a code wall, it is moved here --> https://paste.ubuntu.com/p/QY7H4PjDQf/
can someone point me in the right direction with creating 'smart' templates? Basically I want to create some kind of 'auto-fill' template, but my templating skill is lacking. I basically want to create a template sensor like 'auto-entities' card, that populates the sensor (if that's possible).
So this code, will be shorter and I don't have to update it each time I install a new sensor. Code is above this post
@north acorn Rule #6: Spam will not be tolerated, including but not limited to: self-promotion, flooding, text walls (longer than 15 lines) and unapproved bots.
Please take the time now to review all of the rules and references in #rules.
That's... slightly over 15 lines. Please pay attention to the rules.
What you want is maps. Here's an example (not quite what you're after but it's a starting point):
{{ states | map(attribute="entity_id") | map('regex_search','switch\.bedroom.*') | select('true') | list | count }}
It'll count up how many entities match that pattern.
thanks for the advice! So I can use that kinds of templates for a template sensor if I understand correctly right?
follow up question: is it also possible to use multiple variables to search, to look into multiple entity_id types? And to also tie in the state (so to only show matching entities that are also on)?
Where can I define a unit of measure? I want to make it handle W (Watt) as number.
how to create input_datetimes for - 1060 seconds before sensor as my template only able to triggered manually please
https://paste.ubuntu.com/p/cS5zXxtRH5/
still confuse creating input_datetimes in config.yaml
input_datetime:
sholat_subuh:
seconds: 1060
haven't had luck googling, reading stuff, or just testing things out, trying to use and operator in notify message...simplified message that works is message: '{% if is_state("sensor.sensor2", "12") %} "Test Alert for Kitchen Alarm" {% elif is_state("sensor.sensor3", "12") %} "Test for Basement Alarm" {% elif is_state("sensor.sensor4", "12") %} "Test for Hallway Alarm" {% endif %} trying to use an and function alongside these something like message: '{% if is_state("sensor.sensor2", "12") %} "Test Alert for Kitchen Alarm" {% elif is_state("sensor.sensor3", "12") %} "Test for Basement Alarm" {% elif is_state("sensor.sensor4", "12") %} "Test for Hallway Alarm" {% endif %} suggestions what terms i'm not searching for to try and find examples?
dev tools
templating
There are links at the top for jinja and the built in HA jazz
templating examples don't seem to quite follow the same format in message:, will read over it again
or at least haven't figured out where to put and || etc
thanks
50/50 is just a syntax i'm missing lol
look at jinjas examples as they will focus on syntax rather than the HA particulars
awesome
what are you trying to and?
trying to give a message: if sensor1 and sensor2=0
message: '{% if is_state("sensor.sensor1", "0") and is_state("sensor.sensor2", "0") %} "Test Success" {% endif %}'
trying to figure out where to put an and operator
also can't seem to get the multi-line strings working in the message: but that's secondary after i figure out the and
ha, so i did have it right, ya, was just a syntax thing, % before { gets me often typing fast =/
awesome, thanks for pointing that out
and operator working just fine now
way i remember it:
{% %} logic statements
{{ }} print statements
multi line a bit wonky, may try the literal \n escapes, but at least my full single line stuff is working
gotta strip the newlines from your logic blocks
{%- -%}
that'l ensure that they would render completely inline
@ivory delta
earlier you posted this : "{{ states | map(attribute="name") | map('regex_search','light.bed.*') | select('true') | list | count }}" and I can't figure out what's it's supposed to do
i think that was mono
it returns zero for me, and i can't find any docs on the map function
Ooops. you are right
oh, I cahnged name from entity_id
I have been trying to get it to do anything beside error or "0"
takes all states in the system and pulls out their friendly name if it exists and the entity_id if it doesn't and makes a list. Searches that list for items that contains light.bed in their name as a list of true/false pulls out the trues maps it to a list and then gives a count
probably a better way to do it would be
{{ states.light | map(attribute="entity_id") | map('regex_search','light.bed.*') | select('true') | list | count }}
would be better to force the entity_id since that is what is getting tested against
that would be a count of the entities with light.bed in their name
dunno what the practicality of that would be but it is a thing
well, I can't get it to work, which is what's bothering me
I like to remove pipes from the back and work my way to the front to understand what is happening along all of the pipes
'just easier to sort things when you can see it
I've tried that also
back to list gives me " []" and removing list gives me "<generator object select_or_reject at 0x7fd350272dd0>"
anything with the map command dies
what's the full thing?
huh?
Ok, this is straight from the docs: {{ users | map(attribute="username", default="Anonymous")|join(", ") }}
so do you get a bunch of anon, anon, anon?
no, nothing. except the errors I just listed
add the | list back on the end and remove the stuff before it, sorry
i don't get anything back for {{ users }}
I populated users with a for persons
Ignore me. I don't want to interrupt phnx helping you
{{ states.person |list }}
ha, it auto formatted it for me once i saved the automation message: >- {% if is_state("sensor.first_alert_brk_brands_inc_zcombo_smoke_and_carbon_monoxide_detector_alarm_type_4", "12") and is_state("sensor.first_alert_brk_brands_inc_zcombo_smoke_and_carbon_monoxide_detector_alarm_level_4", "0") %} "Hallway Alarm Test" {% endif %} title: Smoke Alarm - Kitchen
i entered it as single line, HA is telling me i should use the multiline eh
lol
@thorny snow i'm having a hard time pulling attributes from those objects
they might have values mapped out weirdly
as I said, this is straight from the docs, and is not working for me: {{users|map(attribute="username", default="Anonymous")|join(", ") }}
when I populater with users
it's weird
map seems broken for me
phnx, the user thing isn't what he is actually even trying to do, right? just an example of the same sort of thing
map works fine
I feel like I am missing something, sorry 😛
is that regex off?
well, it's using a dot, but it shold be escaped.. finctionally the same
map generally works but i think there's something up with this object. the __repr__ that you're seeing isn't showing direct attributes
I am kinda not even seeing the purpose, when can't we just easily pull attributes without map?
easily evaluate their state, list and count them
yeah the person object really doesn't have much on it
those aren't attribs of person
you can only get things that are marked as @property
you can without a map. the map just pulls all of them at once
person was just a bad thing to start with
hahah figures
the person object is really limited
{% for person in persons %}
{{ state_attr(person.entity_id, 'friendly_name') }}
{% endfor %}
that works
I see that!! So that regex just looks at the entire objext and returns a count of the true...
nah, the regex is a test so that returns true/false on its own
if the regex matches on each
final message template turned out very nicely, entire alert for the first alert zcombo (first gen, not G) smoke alarms works well
thanks for the assistance, hope i can find a couple threads to update as others definitely have had issue getting these to play nice lol
So, I've tried some more after figuring out I can use the Developer Tools to test my templating (that took me a while...). Maybe someone can tell me why this isn't working:
{%- if is_state("input_select.radio_station", "Spotify") -%}
{%- set music_type = 'Spotify' -%}
{%- else -%}
{%- set music_type = 'Radio' -%}
{%- endif -%}
{%- set service_data = {'Spotify': {'entity_id': entity, 'uri': 'spotify:playlist:29aiPfdrGUh6TDEjvsJV3r', 'random_song': 'true'}, 'Radio': {'entity_id': entity, 'media_content_id': channel, 'media_content_type': 'audio/mp4'}} -%}
{{ service_data[states(music_type)] }}
If I use {{ service_data[states('input_select.radio_station')] }} it works (as long if its set to Spotify), but I can't get it to work with a custom variable. {{ service_data[states('Spotify')] }} also fails. I'm not sure how to declare the custom variable in the last line
That makes total sense. Thanks @deft timber ! That solved the last piece
Hmm, perhaps it didn't. I know the stuff gets outputted correctly but I still receive an error after loading my script. See the script and error: https://pastebin.com/kbHcR1e9
Could you try replacing data_template with data ? this has changed some versions ago
not sure it will change your issue though
Same error unfortunately. If I try to specify the data manually under data_template it works as expected
I understand from the error that you cant return a dictionary as you do, but that you should do something like this:
data:
entity_id: >-
{{ ... }}
media_content_id: >-
{{ ... }}
media_content_type: >-
{{ ... }}
and split yor template in 3
The problem with that approach is that depending on the service I call (either spotcast.start or media_player.play_media, it requires different values for data. spotcast.start won't accept media_content_type for example and wont run it I specify it
That's why I was hoping I could use a dictionary as service data
Maybe a choose: is necessary then
I could do it with an automation, but then it'll get triggered on the input_select change, where I want to start it when executing the script
Hmm, didn't know choose: will look into that, thanks
hi.... i have a working template if i check in developer tools, but in card it doesn't show the values https://pastebin.ubuntu.com/p/VHdPmH63Sr/
modified like https://pastebin.ubuntu.com/p/7FbxKKvQ4j/
Thanks @deft timber, conditions/choose was the solution in the end. Took me some struggling but I managed to get it working 🙂 https://pastebin.com/TDgWUWcc is the final script
Some redundant code still, but that's something for later. At least now my lovelace multi-room-audio selector is working 🙂
You can use variables to avoid duplicating codes https://www.home-assistant.io/docs/scripts/#variables
And the last template could be written this way:
media_content_id: >
{% set radios = {"NPO Radio 2": "https://icecast.omroep.nl/radio2-bb-mp3",
"Veronica": "https://20723.live.streamtheworld.com/VERONICA.mp3",
"3FM": "http://icecast.omroep.nl/3fm-bb-mp3",
"Sky Radio": "https://19993.live.streamtheworld.com/SKYRADIO.mp3",
"RTV Oost Radio": "http://streams.rtvoost.nl/audio/oost/mp3",
"NDR 2": "http://www.ndr.de/resources/metadaten/audio/m3u/ndr2.m3u",
"Antenne": "http://vip-icecast.538.lw.triple-it.nl/WEB17_MP3",
"Star FM": "http://85.25.209.152/berlin.mp3"} %}
{{ radios[states("input_select.radio_station")] }}
A (little) bit clearer 🙂
Thanks again for the feedback! Will incorporate the last piece of code and read up on deduplication of code
Hi all ... I'm struggling to fathom out a template sensor which I think I need to use to add a unit_of_measure for an image_processing.sevensegment_ocr_seven_segs SSOCR value. Fair amount of googling and referencing the template example at https://www.home-assistant.io/integrations/seven_segments/.
- platform: template sensors: power_meter: friendly_name: "Electricity monitor" unit_of_measurement: 'kWH' value_template: "{{ states('image_processing.sevensegment_ocr_seven_segs') }}"
I can't find how to access that sensor.
I'm very new to HA and struggling to get my head around templates. Any pointers, please? Keen to fathom this out because I will use it plenty in future I'm sure.
I don't know if it a copy-past issue but your indentation is wrong
should be```yaml
- platform: template
sensors:
power_meter:
friendly_name: "Electricity monitor"
unit_of_measurement: 'kWH'
value_template: "{{ states('image_processing.sevensegment_ocr_seven_segs') }}"
and you can check if your sensor is well created in the
Tool > State screen
Thank you ... could be blasted indentation ... thanks for th pointer - restarting now.
Easy when you know how eh! Thanks again.
sorted
hi, is it possible to template the automation trigger?
trigger:
- platform: state
entity_id: group.lighting_~area
to: "on"
this wont work
where is your area defined ?
you can create a template trigger
trigger:
- platform: template
value_template: "{{is_state('group.lighting_'~area, 'on')}}"
area is defined in variables in the same automation. i will try that again
that does not work, the automation does not trigger. but no error btw
It should work :-p. Can you share the entire automation?
oh you dont want that
if you replace the template with:
trigger:
- platform: template
value_template: >
{% set area = "what_area_should_be"%}
{{is_state('group.lighting_'~area, 'on')}}
does this work ?
to check if it comes from the definition of the area
https://pastebin.com/fm2bELGM
here is the entire automation
Did you try what I proposed above?
I don't think you can use variables
in trigger
https://www.home-assistant.io/docs/scripts/#variables
*The variables command allows you to set/override variables that will be accessible by templates in actions after it *
I made a test and it does work if you define the variable in the template, not if you define it in the variable: part, so it seems you can't use it in a trigger 😦
mh thats sad... i have to rethink my whole automation then...
too bad we cant template entity_ids too
you can but not using variables define outside of the template
i mean like templating XXXX. in a package for example
input_select:
natural_lighting_mode_XXXX:
ok that you can't 🙂
there are reasons i think
@lunar jasper , it will look like this:
{% set ns = namespace(list=[]) %}
{% for option in state_attr("input_select.playlist_options_filtered", "options") if option != states("input_text.playlist_chosen_random_source") %}
{% set ns.list = ns.list+[option] %}
{%endfor%}
{{ns.list}}
if I understood correctly what you want
Thank you, this community (and you) are awesom
👍
I’m trying to do a between color for my battery badge I’m using the code below at the moment but like to become another approach. If battery is above 60% color green, between 30/60% orange and below 30% red. Anyone know how this can be done. Thx in advance.
:host {
—label-badge-blue: {% if is_state(‘sensor.iphone_battery_level’, ‘> 60’) %} green {% else %} red {% endif %};
}