#templates-archived

1 messages ยท Page 15 of 1

inner mesa
#

and cards are what display things

gray skiff
#

cheers

#

but having a dynamic control center dashboard seems like something that would be doable

inner mesa
#

it's a custom card that fills another card with entities based on the criteria that you specify

#

and no, there's no "official" alternative

gray skiff
#

gotcha

#

clever workaround

#

ok so I'll throw that in and then I'll start banging my head again ๐Ÿ™‚

#

@inner mesa Is HACS recommended if I run HA in a container?

#

yeah ignore, see no point not to

inner mesa
#

yes. installation method doesn't matter

uneven pendant
#

@inner mesa I tried to direct message you but couldn't. Just wanted to tell you that you've helped me on more than one occasion and you make a big difference in this community. Thanks again.

inner mesa
#

glad to be of service

thorny snow
#

Yes but I cannot find anything wrong in the code. HA does not give any error. It simply does not read the files at all.

This works:
utility_meter: !include utility_meter.yaml

This does not work:
utility_meter: !include_dir_merge_list utility_meters/
with the same file under that folder

I do not think that it should be
utility_meter: !include_dir_merge_name
(but have tried that to)

inner mesa
#

it's "named", not "name", but I don't do what you're doing and can't offer much more guidance

#

but I continue to contend that it's not expecting a list, and you shouldn't use directives that provide one

raven nebula
#

is this the chat channel to ask about sensor states?

#

oops i see energy i'll go there

#

thanks

thorny snow
obtuse zephyr
#

Is it possible to get a newline in a template to render in a dashboard? It shows up within the Template tester, but that's likely just because the output is in a pre block.

silent seal
#

What does your whole template look like in the YAML?

plain magnetBOT
#

Sadly we're not mind readers (any more anyway, not after the last time we tried). Please share the YAML and any errors so we can see what you've done.

obtuse zephyr
silent seal
#

Pastebin is not loading for me, and it can insert some arbitrary spacing too.

plain magnetBOT
#

Please use a code share site to share code or logs, for example:

Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.

obtuse zephyr
silent seal
#

Just make sure you share the full YAML of your template sensor.

obtuse zephyr
silent seal
#

I needed the whole template, as I can see that's using state: > not state: >- which eliminates one reason why it would be removing line breaks

#

So both Doors and Locks are appearing on the same line?

obtuse zephyr
#

Correct

silent seal
#

I mean, I can think of a way around it, but I suspect that something is being overeager with the -%} tags.

obtuse zephyr
#

Just stripped all of the -s out so there's a truckload of newlines... but they don't show up on an entity card

silent seal
#

I think it's actually that line breaks in template sensor output are removed

#

What would you like to do with multiple lines long term?

obtuse zephyr
#

Just find that formatting to be nicer instead of it being a runon string

silent seal
#

So you want a nice list in say a frontend card?

obtuse zephyr
#

Yup

silent seal
#

You may want to try using templates to create groups instead, or putting the template in the markdown card

obtuse zephyr
#

Gotcha, it does appear to render in a Markdown card. Don't think there's an Android widget for that though, could probably write the template out directly there instead possibly

silent seal
#

I think you can just define the templates for Android widgets separately actually

obtuse zephyr
#

Yeah I can give that a shot, thanks for the ideas

silent seal
obtuse zephyr
#

Heh actually just using the Template widget and echoing out the template sensor brings back the line breaks

silent seal
#

Perfect

tidal meteor
#

I have a couple of timers related to my wake-up schedule / time, i want to show the next active timer on my dashboard.
I have created a template sensor

https://hastebin.com/ijisazavoj.coffeescript

If i try the code segment in the Developer tools / template i see the info i was expecting, but the sensor created by the template reports 'unavailable'

https://hastebin.com/kosalideve.php

What am i doing wrong ?

inner mesa
#

what you described doesn't really match that code

#

I see a few things -

#
  • The namespace seems to be unused
#
  • If any of the timers are active, it always picks the first one in your list of timers (not the next one, or not even an active one)
#
  • You're returning a state object if any timers are active, as shown in the template dev tool, which probably isn't a valid state
hoary wing
#

Does anyone know how i can change the icon of the following? And how to show this state only when its before 0800 ?

โ™ป๏ธ GFT is vandaag!
{% endif %}```
normal berry
#

Can someone help me with an MQTT select command_template?

#

I have options like this: options:
- "0 - Schutzbetrieb" - "1 - Automatik" - "2 - Reduziert" - "3 - Komfort"

#

And I would like to get the value from the beginning to be used in the command_template.

#

I tried this {{this.state.split(' ')[0]}}, but it doesn't give the right result. It always revert to the current state of the select, not the new one.

prime kindle
#

How can we replace a substring in template conditions.
This is not working:-
{% set state = states('sensor.pantry_items') %}{{ state | states('sensor.pantry_items').replace("1: Canned Tomato", "") }}

obtuse zephyr
#

You can either do {{ state | replace("1: Canned Tomato", "") }} or {{ state.replace("1: Canned Tomato", "") }}, but using the string result as a filter will not work

obtuse zephyr
sacred sparrow
#

Is it possible to make a icon a template like: {{ mdi:light }}

obtuse zephyr
#

are you going to use a variable there? I think depending where you use it, you could output an icon

silent seal
velvet sigil
#

How can I make a last seen status out of {{states.binary_sensor.voron.last_updated}}

#

This one returns state as 2022-11-08 12:46:22.612422+00:00

plain magnetBOT
silent seal
#

(Though make sure not to format it if you set the device class, instead filter it as a timestamp)

#

So you'll probably want:

template:
  - sensor:
      - name: "Voron Last Updated"
        unique_id: "voron_last_updated"
        device_class: "timestamp"
        state: >
          {{ states.binary_sensor.voron.last_updated | as_timestamp }}

Or similar

velvet sigil
#

Thank you so much.
But I am still confused how do I convert it to last see.
as {{ states.binary_sensor.voron.last_updated | as_timestamp }} returns 1667912032.622624

silent seal
#

Yes, but by setting the device class of timestamp HA automatically interprets that correctly so when you add the template sensor you will see the date and time

#

a timestamp is in this case a unix timestamp, seconds since January 1st 1970

velvet sigil
#

I am starting to understand

#

So if i want to make it to be time elapsed from last change I should do smth like now() - sensor.voron_last_updated? ?

silent seal
#

You'll need to parse the last_updated into a datetime for that

#

Oh wait, that's your new sensor

#

If you just want time since it last updated, you could put that in the original template sensor. But if you just want to display it in the frontend, I'd put it in a Markdown card ๐Ÿ™‚

velvet sigil
hoary wing
#
cards:
  - type: custom:mushroom-title-card
    title: |2-
                 {%- if now().hour < 12 -%}Goedemorgen
                 {%- elif now().hour < 18 -%}Goedemiddag
                 {%- else -%}Goedeavond{%- endif -%}, {{user}}
    subtitle: |-
      {% if is_state("sensor.dar_today", 'gft') %}
      โ™ป๏ธ GFT is vandaag!
      {% endif %}
      ๐Ÿ’ก {{ states.light
      | rejectattr('attributes.entity_id', 'defined')
      | selectattr('state', 'eq', 'on')
      | list | count }} Lampen aan```
#

This is the card i use

silent seal
hoary wing
#

i want to change the GFT icon and light icon if possible

#

Both are emojis :p

#

Also like to use a plex emoticon

velvet sigil
#

so title will show las time elapsed since last change

silent seal
silent seal
hoary wing
silent seal
#

You should check the docs for the card to see what it says about icons, as you didn't actually define the icon

#

If it is from an entity, you will need to customise the entity, and that's where the template:

icon: >
  {% if is_state("sensor.dar_today", 'gft') and now() < today_at("08:00") %}
    mdi:recycle
  {% else %}
    mdi:calendar
  {% endif %}

Would come in

velvet sigil
silent seal
#

Then you can remove | as_datetime, I forgot that's a valid date time

hoary wing
silent seal
prime kindle
obtuse zephyr
#

Then your replacement string isn't correct

#

Share some details about the output

prime kindle
# obtuse zephyr Share some details about the output

Currently I am using the condition as:-
{% set state = states('sensor.pantry_items') %}{{ state.replace("Canned Tomato", "") }}

And state is:-

"state": "[Canned Tomato, Paper Towels, Tomato Sauce, Ketchup, Mayo, Sugar]",'

plain magnetBOT
inner mesa
#

A wait_template is expecting an expression that returns true or false, not a list

prime kindle
inner mesa
#

but it doesn't make sense in that template

#

are you just trying to remove an item from a list?

prime kindle
inner mesa
#

that's pretty weird

#

{{ "[Canned Tomato, Paper Towels, Tomato Sauce, Ketchup, Mayo, Sugar]"|replace('Canned Tomato, ', '') }} works fine for me

#

it looks like some broken, malformed JSON. Anyway, this also works:
{% set data = {"state": "[Canned Tomato, Paper Towels, Tomato Sauce, Ketchup, Mayo, Sugar]"} %} {{ data.state|replace('Canned Tomato, ', '') }}

prime kindle
inner mesa
#

if you're getting that via MQTT, it's probably proper JSON there and is being turned into a mangled string when you make it the state of a sensor

#

it feels like you're approaching this in the wrong way

#

when it comes in via MQTT, make it an attribute and treat it as the JSON object & list that they are

prime kindle
inner mesa
#

ok, so I've shown you how to do that

plain magnetBOT
sacred sparrow
#

I restarted my server and my template sensor is showing as "unknown"

    - platform: time
      at: "05:00:00"
      id: 5am
    - platform: state
      entity_id: sensor.outside_home_temperature
  sensor:
    - name: "Outside Min Temp"
      unique_id: outside_min_temp
      availability: "{{ states('sensor.outside_home_temperature') | is_number and states('sensor.outside_home_feels_like_temperature') | is_number }}"
      unit_of_measurement: "ยฐC"
      device_class: temperature
      state: "{{ iif (trigger.id == '5am' or states('sensor.outside_home_feels_like_temperature') | float < states('sensor.outside_min_temp') | float, states('sensor.outside_home_feels_like_temperature'), states('sensor.outside_min_temp')) }}"```
sensor.outside_home_temperature = 26.2
sensor.outside_home_feels_like_temperature = 25.9
and is there a way of if its showing up as unknown it just shows up as "-"
prime kindle
#

Can we write any condition in 'template condition' of the automation by which we can replace the state of a sensor?

marble jackal
prime kindle
marble jackal
#

That really depends on the integration which created the sensor, there could be a service call provided by the integration to amend the values in the sensor

plain magnetBOT
flint wing
#

After your advice to dive into the new syntax, I gave it a try and tried to convert my legacy format code.

Here is the previous code with legacy syntax:

sensor:
  - platform: template
    sensors:
        duree_ecoulement_eau_principale:
          friendly_name: Durรฉe d'รฉcoulement de l'eau principale
          unit_of_measurement: "sec"
          value_template: >
            {% set t = this.state if states('input_boolean.eau_principale_on_off') == 'off' else now().timestamp() - states.input_boolean.eau_principale_on_off.last_changed.timestamp() %}
            {{ t | round(2, 'common') }}
#

And here is the update code with new format?

template:
  - sensor:
    - name: Durรฉe d'รฉcoulement de l'eau principale TEST
      unit_of_measurement: "sec"
      state: >
        {% set t = this.state if states('input_boolean.eau_principale_on_off') == 'off' else now().timestamp() - states.input_boolean.eau_principale_on_off.last_changed.timestamp() %}
        {{ t | round(2, 'common') }}

Does it seems legit?

silent seal
plain magnetBOT
sacred sparrow
willow rapids
sacred sparrow
marble jackal
#

That's probably your problem, your template runs in error when then second trigger triggers

#

As it has no trigger id

#

Oh no, wait that can't be it, it has an id by default, 1 in this case

sturdy yarrow
#

Does anyone know if it's possible to add icons to templates? Right now I have this template, and I would love to change "Date:" with an icon..
{% set input = as_datetime(states('input_datetime.helper_dato_for_hjemmekontor')) %}
{% if now().date() < input.date() %}
Date: {{ input.strftime('%d %B') }}
{% endif %}

#

If I just add the mdi:someicon it will just show that text instead of an actual icon...

marble jackal
#

You can't directly, I believe there is some way to use mdi icons in strings, but it is easier to use emoji

silent seal
#

You need to set the icon of the entity, but you can't do it in the same template as the state

prime kindle
#

How can I write 2 conditions back to back here, the following code is not working:-
service: mqtt.publish
data:
ย  topic: pantry_items
ย  payload_template: >-
ย  ย  {{ states("sensor.pantry_items") |
ย  ย  regex_replace(find="Canned Tomatoes,", replace="", ignorecase=False) }}
ย  ย  {{ states("sensor.pantry_items") |
ย  ย  regex_replace(find=states("sensor.pantry_items"), replace=states("sensor.pantry_items")+" Canned Tomatoes, ", ignorecase=False) }}

silent seal
#

Weren't you asking about this yesterday? And is pantry_items an array or a malformed JSON string?

distant plover
#

I have a whitelist of mac addresses stored in an attribute of a template sensor like this: ['11:11:11:11:11:11', '22:22:22:22:22:22', '33:33:33:33:33:33']. I then have an automation with a condition checking if a mac is in this whitelist. {% set allowlist = state_attr("sensor.asusrouter_allowlist", "list") %} {{ trigger.event.data.mac.upper() not in allowlist }}
Question is if I can structure the whitelist like so ['nameOfDevice1', 'mac1, 'nameOfDevice2', 'mac2' ...] and still check condition against the whitelist somehow. I need it so I can easier see what MAC address belongs to what device.

#

When I think of it, for this purpose I guess I can just make the whitelist exactly like that and it would still work. The condition would check against 'nameOfDevice1' which is not a valid mac address and just move on. But that's a bit silly.

#

Is there a different way I should store the list in order to keep both device name and mac together?

mighty ledge
distant plover
#

Nice! Perhaps a silly question but would it also be possible to skip the identificator like this [ { 'nameOfDevice1':'11:11:11:11:11:11'}, {'nameOfDevice2': '11:11:11:11:11:12'} ] and then somehow get just the mac by using something like trigger.event.data.mac.upper().[1]? If you understand what I mean... ๐Ÿ˜†

#

I mean like asking for the second part of each 'pair' ๐Ÿ˜›

mighty ledge
#

yes

#
[ ('nameOfDevice1', '11:11:11:11:11:11'), ('nameOfDevice2','11:11:11:11:11:11') ]
#

and

#
{% set allowlist = state_attr("sensor.asusrouter_allowlist", "list") %}
{% set name = allowlist | selectattr('1', 'eq', trigger.event.data.mac.upper()) | map(attribute='0') | list | first | default %}
{{ name is not none }}
#

makes it harder to read though ๐Ÿ˜‰

distant plover
#

Lovely! Thanks! Harder to read perhaps, but easier to modify the whitelist ๐Ÿ˜„

mighty ledge
#

not necessiarly

#

are you using yaml to create this list?

#

how are you creating the attribute?

distant plover
#

Just modifying the attribute in file editor in yaml, yes

mighty ledge
#

can you show me

distant plover
#
template:
    - sensor:
      - name: AsusRouter Allowlist
        unique_id: asusrouter_allowlist
        state: True
        attributes:
          list: >
            {{ ["11:11:11:11:11:11", ... }}```
mighty ledge
#

You should be able to do...

#
  - sensor:
      - name: AsusRouter Allowlist
        unique_id: asusrouter_allowlist
        state: True
        attributes:
          list:
          - name: abc
            mac: 11:11:11:11
          - name: xyz
            mac: 11:11:11:11
#

where as if you made that a tuple

#

it would be

#
  - sensor:
      - name: AsusRouter Allowlist
        unique_id: asusrouter_allowlist
        state: True
        attributes:
          list:
          - - abc
            - 11:11:11:11
          - - xyz
            - 11:11:11:11
#

or you can go with the way you're doing it

distant plover
#

Awesome ๐Ÿ™‚ Thanks again. I'll consider my options.

flint wing
plain magnetBOT
normal moat
#

and it seems I need to learn how to write code on discord ๐Ÿ˜ sorry about that (I dont use that feature very often)

mighty ledge
#
{% set lowest = state_attr('sensor.nrgi_idag', 'prices') | selectattr('isLowestPrice', 'eq', True) | list | first | default %}
{% if lowest %}
  {{ lowest.localTime }}
{% else %}
  No lowest time
{% endif %}
real idol
#

Would it be possible to get a number of entities from a specific integration?

mighty ledge
#

{{ integration_entities('zwave_js') | count }}

real idol
#

sweet, thanks :)

mighty ledge
#

covered in the docs ๐Ÿ˜‰

normal moat
#

Thank you @mighty ledge

hoary ether
#

Any way to include an input_number state into an automation alias?

mighty ledge
#

nope, not possible

hoary ether
#

was just wondering ๐Ÿ™‚

pine belfry
#

this is driving me crazy, why cant I apply a filter here? {{ states.binary_sensor
| selectattr('attributes.device_class', '==', 'window')
| list }}

desert tangle
#

Any idea why doesnt my state images work on 'picture-element'

#

well, they disappeared after core and supervisor update

obtuse zephyr
pine belfry
#

let me check

#

Entity ID [<template TemplateState(<state binary_sensor.ewelink_ds01_c29f1325_ias_zone=off; device_class=window is an invalid entity ID for dictionary value @ data['entities']

#

at least i get an error back now

#

i guess i need a map

#

finally

#

@obtuse zephyr thank you so much for pointing me to the right direction

obtuse zephyr
#

You bet, np

cyan star
#

guys, i'm beggig for help. Having such mqtt payload (json): https://pastebin.com/jvnwBLpe I'm trying to create separate sensors for every item in 'harmonogramy' list depending on value of $.harmonogramy[i].frakcja.id_frakcja I would like to pass $.harmonogramy[i].data to strptime. I guess selectattr and possibly | map | dict is way to go, but struggling to set this up. Any hint?

marble jackal
#

Or a string maybe, can't really remember

sonic nimbus
#

Hello,
I want to put a template condition which will check if some light from group of lights, or some media_player or swith from their respective groups is at least one turned on, to trigger automation
how can I do this
For examle I have script: "Goodbye Home" where I turn off everything in my house. the trigger is changing my zone from House to Away or other zone, so basically I want to trigger this automation only if there need to do (at least one light, or switch, or media_player is turned on)

distant plover
#

Perhaps because of the way I create the allowlist? - sensor: - name: AsusRouter Allowlist unique_id: asusrouter_allowlist state: True attributes: list: > [ ('name1','11:11:11:11:11:11'), ('name2','22:22:22:22:22:22'), ('name3','33:33:33:33:33:33')]

mighty ledge
#

you might have to change the () to []

#

it depends on what the parser allows

#

well, no that works, so it's something else

#

make sure the attribute is not a string

distant plover
#

I tested by doing this: {% set allowlist = state_attr("sensor.asusrouter_allowlist", "list") %} {% set name = allowlist | selectattr('1', 'eq', '11:11:11:11:11:11'.upper()) | map(attribute='0') | list | first | default %} {{ name is not none }}

#

How do I do that?

mighty ledge
#

what does

#

{{ state_attr("sensor.asusrouter_allowlist", "list") }} return in the template editor?

distant plover
#

The whole [ ('name1','11:11:11:11:11:11'), ('name2','11:11:11:11:11:12'), ('name3','11:11:11:11:11:13'), ('name4','11:11:11:11:11:14').... ] (macs swapped out )

mighty ledge
#

then ya did something wrong

#

it should show up like

#
[
  [
    "name1",
    "11:11:11:11:11:11"
  ],
]
#

FYI mac addresses aren't something that need to be hidden

distant plover
#

I'm gonna try with " instead of '

mighty ledge
#

that's not going to make a difference

#

you'r emost likely missing a quote

#

or some other character

distant plover
#

I'll have a look

#

Hmm... some of my devices are named name1 [bedroom] ...Perhaps I need to treat those differently

mighty ledge
#

can you just post the entire unaltered list?

#

I'll tell you what's wrong

distant plover
#

Let me just try a bit more first... ๐Ÿ˜‹

mighty ledge
#

suit yourself, but I can tell you it's not related to your names

distant plover
#

I cut it down to use the examples and now the value looks like you said [ [ "name1", "11:11:11:11:11:11" ],

#

But I still get UndefinedError: str object has no element 1 on ```{% set allowlist = state_attr("sensor.asusrouter_allowlist", "list") %}
{% set name = allowlist | selectattr('1', 'eq', '11:11:11:11:11:11') | map(attribute='0') | list | first | default %}
{{ name is not none }}

buoyant pine
#

|| MAC addresses aren't sensitive info btw ||

keen swan
#

Hi, i could really do with some help here, I have a binary sensor, but i want to check 2 states, and the both must be TRUE before setting ON state, i dont know how to and and AND between the two IF's

#
{% if state_attr("sensor.dallas_mavericks", "opponent_name") == "Grizzlies" %}
{% if states("sensor.dallas_mavericks") != 'PRE' %}
            Off
          {% else %}
            On
          {% endif %}
          {% endif %}
inner mesa
#

'and'

silent seal
#
{% if is_state_attr("sensor.dallas_mavericks", "opponent_name", "Grizzlies") and not is_state("sensor.dallas_mavericks", 'PRE') %}
#

Be careful there, you're mixing quotes too. Some are " and some are '

inner mesa
#

'I'll take overthinking for $100, Alex'

silent seal
#

๐Ÿ˜‚ true true

distant plover
#

So I did {% set mylist = [('name1','bla1'),('name2','bla2'),('name3','bla3') ] and ```{% set mylist2 = state_attr('sensor.asusrouter_allowlist', 'list') %}

silent seal
silent seal
#

Because it looks like malformed JSON to me.

distant plover
#

Both show [ [ "name1", "bla1" ], [ "name2", "bla2" ], [ "name3", "bla3" ] ]

keen swan
silent seal
silent seal
distant plover
#

Here is my yaml in configuration: - sensor: - name: AsusRouter Allowlist unique_id: asusrouter_allowlist state: True attributes: list: "[('name1','bla1'), ('name2','bla2'), ('name3','bla3')]"

silent seal
#

Question: Why are you defining this in YAML like that?
Second question: Why is the JSON both malformed and in a string?
Third question: What are you trying to do?

#

The third is probably the most important question here

distant plover
#

Haha. I'm trying to create a whitelist to compare an event to but because of the error I'm trying to break it down. I wanted a nice list of "device name, mac address" that could be easily edited when I needed to.

silent seal
#

I'd highly recommend putting that in a database somewhere and looking it up rather than storing it as attributes in a template

distant plover
#

Initially I had it one line for each device but just to make sure the issue wasn't a multiline issue I put it on one line

#

I do use an integration. I use an event that integration has for devices connecting but want to compare it to a whitelist. A template sensor seems nice. ๐Ÿ™‚

silent seal
#

But another way:

  - sensor:
      - name: AsusRouter Allowlist
        unique_id: asusrouter_allowlist
        state: True
        attributes:
          name1: 'bla1'
          name2: 'bla2'
          name3: 'bla3'
#

Or nest those names under list, something like that.

mighty ledge
#

you have to use yaml, or json

#

or a template

#

you're making it a string, which will always fail

#

remove the outside quotes, or put it in a template, or make it into json

silent seal
#

Petro is very good at templates, so I'd recommend listening to him ๐Ÿ™‚

distant plover
#

File editor says "missed comma between flow collection entries (257:33)" when I remove the " "

mighty ledge
#

well, you refuse to actually show what you're putting in that field, so I can't help

#

i've said it multiple times that you're messing something up

#

post it and I'll show you

distant plover
#

What I pasted IS what I have now. I removed all the real stuff and now use just 3 lines.

mighty ledge
#

none of it is sensitive information, so i'm not sure why you're reluctant

mighty ledge
#

lose the outsize quotes

distant plover
#

 254 |         unique_id: asusrouter_allowlist
 255 |         state: True
 256 |         attributes:
 257 |           list: [('name1','bla1'), ('name2','bla2'), ('name3',' ...
---------------------------------------^
 258 | ```
mighty ledge
#

or keep the outside quotes and add the {{ }}

distant plover
#

Maybe a bug in File editor?

silent seal
#
  - sensor:
      - name: AsusRouter Allowlist
        unique_id: asusrouter_allowlist
        state: True
        attributes:
          list: [{'name1','bla1'}, {'name2','bla2')}, {'name3','bla3'}]

is my guess at what you should be doing. But if you put an apostrophe in a device name...

mighty ledge
#

well, {} is a dictionary

#

he's trying to keeep them tuples

silent seal
#

Why tuples? He was trying to look up the bla1 by name1 just now ๐Ÿคช

mighty ledge
#

๐Ÿคทโ€โ™‚๏ธ that's what he wanted

silent seal
#

I stand corrected, he was trying to look it up by index.

#

Which makes no sense to me either to be honest.

mighty ledge
#

it's possible what thefes said earlier is also true, attributes might require templates and nothing else

silent seal
#

Yup, that would make sense. I'd go for an API call to look this up myself.

marble jackal
#

I'm on holiday right now, so I can't really test it, but I ran into that in the past

mighty ledge
#

it would just be the config validation, which TBH shouldn't be a restriction

#

I just got back from holiday

#

spooling up my devbox

marble jackal
#

It's a bit inconvenient to create a test template sensor in mobile

keen swan
marble jackal
#

Maybe the easiest way is to create it on GitHub and then pull it to my config

silent seal
#

I'm just cooking, but will pull out my iPad shortly

#

Stupid kitchen having limited counter space ๐Ÿ˜›

mighty ledge
#

or single value

#

can't be a complex object

#

odd restriction, it's only the validation.

silent seal
#

So, MQTT sensor?

mighty ledge
#

nope, he just needs {{ }}

silent seal
#

Gotcha

marble jackal
mighty ledge
#
    attributes:
      bar: "{{ [('a', 'b'), ('c', 'd')] }}"
distant plover
#

Well that seems to have helped yes, but it's not working properly for {% set allowlist = state_attr("sensor.asusrouter_allowlist", "list") %} {% set name = allowlist | selectattr('1', 'eq', 'bla1'.upper()) | map(attribute='0') | list | first | default %} {{ name is not none }} It's returning True with both 'bla1' and 'asdadas'.

mighty ledge
#

well yeah

#

I mimic'd what you wanted in your previous post, which was a condition

distant plover
#

Ah, so it probably works but not when I replace it with a string in dev tools?

#

If I understand you correctly

mighty ledge
distant plover
#

Ok. I just expected it to return False if MAC was in allow list and True if not.

mighty ledge
#

remove the not

distant plover
#

Yeah, that's ok, but I still don't understand how it can return True with both 'bla1' and 'asdasdad'. But I'll put it as a condition and see how it goes. ๐Ÿ˜„

mighty ledge
#

change the default to default(none)

#

then it'll work as expected

distant plover
#

Yey! ๐Ÿ˜„

#

Thanks a lot everyone.

low blaze
#

I have a template entity with some if statements, can I include a โ€œforโ€

#

Example right now itโ€™s if x>7 and switch = on, then Ok

#

Can I write it so that it means

#

If x>7 for 30 seconds and switch = on?

#

Or do I need to make a helper variable and an automation that flips/sets the helper variable for me and then base off that helper?

inner mesa
#

you should create a trigger-based binary_sensor with a numeric_state trigger and a for: and base it off of that

atomic blade
#

Is there a way to get the non-domain portion of an entity_id?

#

Like an attribute I'm not aware of or something

#

I have something like this and I'm trying to get the notification id (which is the part after the .)

{{
  states
  | selectattr('domain', 'eq', 'persistent_notification')
  | map(attribute='entity_id')
  | list
}}
#

Otherwise I'll just use a regex I suppose

inner mesa
#

It's the object_id

#

See the state object docs

atomic blade
#

Ah perfect thanks, cuz I was failing at the regex part. Just to educate myself, how would that actually work using a regex? regex_findall seemed like it might be but it doesn't seem to be working as I expected

#

I think really I want to use a map there, because I'm trying to modify the data. I'm kinda at a loss though

#

map('replace', 'persistent_notification.', '')

#

Though I was kinda hoping for a more generic solution using a regex. Something like [^.]*, but replace just takes a substring

inner mesa
#

Look into regex_replace

atomic blade
#

Cool, thanks for the help rob

#

Think I got my full NR flow to clear persistent notifications based on message

upper raptor
#

I'm trying to turn a list of entity ids into their device names. I thought I could do:

my_list | device_attr("name_by_user")

but apparently device_attr is not a filter. Any suggested alternatives?

waxen rune
silent vector
#

Is there a way using a template to extract a configuration parameter/value of a Z-Wave device?

cyan star
#

does anybody know if there is any convenient way to debug value_template j2 templates based on 'mocked' or real values that come from mqtt topic? Developer tools/template is not way to go in this case

#

i tried to {% set var = value %} but it's not the same as the var is of type str not json

upper raptor
elder stag
#

Hi smart peoples... I want to create a template so that I can create card on my dashboard... It is for my Solar inverter's battery state of charge, anyways what I need to do is the state of charge shows as a percentage.. What I want to die is show the state of charge time to 35% from one hundred percent and also vise versa? I have no clue of to do this

mighty ledge
mighty ledge
mighty ledge
cyan star
#

Thank You!!

upper raptor
upper raptor
mighty ledge
#
{% set ns = namespace(names=[]) %}
{% for e in mylist %}
  {% set ns.names = ns.names + [ device_attr(e, 'name_by_user') ] %}
{% endfor %}
{{ ns.names }}
upper raptor
mighty ledge
#

it's not intentional

#

nothing is intentional with templates

upper raptor
#

LOL

mighty ledge
#

just missing functionality

upper raptor
#

just wondering if it's as simple as a PR that adds

self.filters["device_attr"] = pass_context(self.globals["device_attr"])
mighty ledge
#

yep, that would be about it

#

but you're still using it wrong in jinja

#

if it was a filter, this would be the correct way.

{{ mylist | map('device_attr', 'name_by_user') | list }}
upper raptor
#

cool. Why is it better than the direct way? I use filters like that all the time

mighty ledge
#

it's not better, the method only acccepts a single string as an input

#

so if it was a filter, it would still only accept a single string as the first argument

#
first_argument | filter(second_argument)

is functionality the same as

filter(first_arugment, second_argument)
#

that's the only difference between a filter and a function/method

#

but filters can be used in map and other functions

#

and device_attr does not accept a list, therefor you'd have to use map.

upper raptor
#

but map itself is a filter with arguments, why is it needed?

mighty ledge
#

because device_attr's 1st argument doesn't accept a list

upper raptor
#

ah, got it

mighty ledge
#

i don't know how else to explain it

#

it accepts 1 item, not a list

upper raptor
#

yeah, I guess all the other filters I'm using are for lists

#

thanks

mighty ledge
#

np

inner mesa
mighty ledge
#

I'd expect 1 - 2 months max

inner mesa
#

You tell me

#

There are a bunch of 'can't be used as filters' functions that I want to fix

mighty ledge
#

BTW, feel free to ping me, IDC about pings

#

and let me know if you don't like pings, i'll stop. However I ping tink on purpose now ๐Ÿคฃ

inner mesa
#

Not offhand, but it's the ones around devices and integrations

mighty ledge
#

ah ok

#

makes sense

inner mesa
#

I love filters, and it just seemed a weird omission

mighty ledge
#

when they are rejected, it's mainly because it doesn't make sense code-wise

#

unless you can show a usecase for it

#

like when using select or selectattr

inner mesa
#

I don't see why you'd want a function without a filter that can act on an iterator

mighty ledge
#

for example, states as a filter was rejected at one point

mighty ledge
inner mesa
#

In any case, I have a PR for device_attr, I think. Will look at others

#

It's a pattern

mighty ledge
#

I'd lump all device ones together and all integration ones together

#

tests and filters

buoyant pine
mighty ledge
buoyant pine
noble hearth
#

Hello, template math type question. I want to divide 2 entities.

#

Does this look correct?

#

template:

  • sensor:
    • name: "Percent Covered"
      unit_of_measurement: "W"
      state: "{{ states('sensor.envoy_20221x_lifetime_energy_consumption') / states('sensor.envoy_20221x_lifetime_energy_production') }}"
buoyant pine
#

you need to convert both to floats

#
{{ states('sensor.envoy_20221x_lifetime_energy_consumption') | float(1) / states('sensor.envoy_20221x_lifetime_energy_production') | float(1) }}
``` replace the `1` with whatever a reasonable default value is for those sensors in the event that one or both of them are unavailable
noble hearth
#

Ok, I have to read up on float. Let me give that a try.

buoyant pine
#

All states are strings, so you need to convert them to numbers first before doing math with them

noble hearth
#

That worked perfect. | round(2) }} at the end should work, no?

marble jackal
#

I assume you want to rond the result, in that case you need to add parenthesis around the formula

mighty ledge
buoyant pine
#

First you unga, then you bunga

inner mesa
buoyant pine
inner mesa
#

It was surprisingly easy and seamless. I realized that all the addons I was running were simply to allow access to HA OS, and then I had my VM mysteriously just shut down twice in a few days. Once it was making my install less stable, I bailed

buoyant pine
#

HA Container is nice. docker-compose is also so easy to use it feels like I'm using a UI

#

I do like YAML though, so that helps I suppose

inner mesa
#

I wrote a small shell script to update HA, so still easy to update with a button

buoyant pine
#

I have some aliases set up and an updater script

inner mesa
#

I also collapsed all my (many) independent containers into a single docker-compose.yaml, and I'm somewhat less enthused about that

#

updating isn't really a one-size-fits-all exercise, and I found yesterday that a single failure broke everything. I've been slowly putting most stuff in a separate profile to allow starting/updating independently

upper raptor
#

just read the conversation and saw that @inner mesa you might have one too? Mine is for device_attr and is_device_attr

inner mesa
#

I found it to be more complicated than just allowing it to be called as a filter

upper raptor
#

hmm, it worked for me

inner mesa
#

you can ignore a bunch of that, as it's related to the other PR

mighty ledge
#

is_device_attr needs to be a test for it to work with select

upper raptor
#

oh, I actually didn't test it with select - just assumed it works

#

I'll chang the description

mighty ledge
#

yeah, well you assumed wrong ๐Ÿ™‚

upper raptor
#

ok, I updated the PR description to something I did test

vast juniper
#

Hi guys, i scraped some date of Internet ' Thursday 10 November 2022' this current string in it, how can i cant it to date? Thanks

inner mesa
#

When I was working on that PR, I had expected that filters would be called separately for each item in the incoming list, but it seemed like they just get called with the whole thing, requiring the filter to iterate. That's why it seemed more complicated. Did I just misunderstand what was going on there?

upper raptor
#

and then it doesn't have to work on a collection, just a single item

inner mesa
#

ok

#

in any case, I'm a fan of any template dev work, so thanks for contributing!

upper raptor
#

let's hope it gets picked up

marble jackal
vast juniper
buoyant pine
#

docker-compose up {service_name}

inner mesa
#

I know, it's just more typing

#

some things I want to update together, some things separately. profiles can help with that

buoyant pine
#

makes sense

inner mesa
#

like unifi has three different containers that are all related

#

npm has 2

buoyant pine
#

makes sense

inner mesa
#

I just don't have a consistent system in place yet

buoyant pine
#

makes sense

marble jackal
vast juniper
proven needle
#

Im trying to create a template sensor with an attribute that is supposed to be a list of objects, {date, value}. I can only seem to get to be a string, and not a real list, that I can use in my frontend for charts and stuff. Any way to do this correct?

fickle kettle
#

From what I understand, a template sensor returns only a single value

proven needle
#

yes, a list will also be a single value, and an attribute can be a list. It will just turn into a string when I use an object

plain magnetBOT
#

Please use a code share site to share code or logs, for example:

Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.

marble jackal
#

Share what you have now @proven needle

lapis flax
#

anyone familiar with scraping data from a local hosted website ? - im trying to scrape some data in a sensor, but having some issues with getting the correct css selector. If anyone could spare a few tips, please feel free to write me a message privately

proven needle
willow rapids
lapis flax
willow rapids
#
  resource: https://www.gasbuddy.com/home?search=68154&fuel=1&stationId=38&maxAge=0&method=all
  scan_interval: 3600
  name: GasBuddy-Costco
  select: 'div#root div:nth-child(1) > span.text__lg___1S7OO.text__bold___1C6Z_.text__left___1iOw3.PriceTrends-module__priceHeader___fB9X9'
#

try that and see if that helps you understand why yours isn't working... or post your code...

lapis flax
#
  • platform: scrape
    name: Storj Bandwith
    resource: http:// removed....
    select: "#app > div > div.scrollable > div.content-overflow > div > div.info-area > section:nth-child(3) > div > p > b"
willow rapids
#

have you tried the select with ' '

lapis flax
#

no. ill try that

#

no change ๐Ÿ˜ฆ

willow rapids
#

I'm certainly no expert. I don't have any local scrapes, mine are all on public sites... but I have 4 and once I got them right I left them alone. I'll wait until someone more knowledgeable can respond.

lapis flax
#

fair enough - thanks for your input anyway ๐Ÿ™‚

willow rapids
#

very welcome

obtuse zephyr
lapis flax
obtuse zephyr
#

Your local page doesn't have auth or SSL or anything on it?

lapis flax
#

No, not That I know off

#

No login required

#

It's a local dashboard from a storj node if your familiar with storj

obtuse zephyr
#

Gotcha, I'm not, I just know a lot of (obviously, not all) local things require some type of credentials before letting you browse the first time

mighty ledge
#

this channel is for jinja templates

lapis flax
mighty ledge
#

it is all templates, but what you're asking about isn't a template

lapis flax
#

Yes it is?

#

A template sensor

#

Using scrape function as the template

#

Or am I missing something

mighty ledge
#

I've yet to see you post any template

#

you're asking about the scrape integration selectors

#

and the configuration for scrape

#

a template will start with {{ }} or {% %}

#

and it will contain jinja code

#

e.g. template

{% set abc = states('sesnor.something') | float(0) %}
{{ abc + 4 }}
#

that's jinja

#

i.e. a template

lapis flax
#

Ahh I see thanks for clearing that up

#

I'll try in integrations

#

I got jinja code covered. Just didn't know that was what it was called

mighty ledge
#

FYI, you can read the channel description for each channel, it will clear up any doubts about where to post.

plain magnetBOT
#
The topic of this channel is:

Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/

This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.

Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs

heavy crown
formal ember
#

http://pastie.org/p/7o0BTUraok6Uh2wR7szoug

Using this for gathering the total power my lighting circuits use. I throw it into the energy dashboard and some days it is showing 500 kwh per day usage. what have I done wrong? all entitles it is pulling the state from are in kWh

mighty ledge
#

well, for 1 I see a power entity in there

#

m

formal ember
#

๐Ÿ˜ฎ

#

i am retarded

#

theres two!

mighty ledge
#

bathroom is in there twice

#

you also have others in there twice

#

FYI, the way you are managing that isn't very nice

#
{% set entities = (
  'sensor.ensuite_ceiling_energy',
  'sensor.ensuite_vanity_energy',
  'sensor.toilet_ceiling_energy',
  'sensor.bathroom_ceiling_energy',
  'sensor.bathroom_fan_energy',
  'sensor.underhouse_storage_energy',
  'sensor.workshop_energy',
  'sensor.toilet_fan_energy',
  'sensor.entrance_chandelier_energy',
) %}
{{ entities | map('states') | map('float') | sum | round(2) }}
#

does the same thing you're doing

#

and then your availability would be

formal ember
#

lots of multiples

mighty ledge
#
{% set entities = (
  'sensor.ensuite_ceiling_energy',
  'sensor.ensuite_vanity_energy',
  'sensor.toilet_ceiling_energy',
  'sensor.bathroom_ceiling_energy',
  'sensor.bathroom_fan_energy',
  'sensor.underhouse_storage_energy',
  'sensor.workshop_energy',
  'sensor.toilet_fan_energy',
  'sensor.entrance_chandelier_energy',
) %}
{{ entities | map('states') | reject('is_number') | list | count > 0 }}
formal ember
#

what is the difference between the two?

mighty ledge
#

first is you sum

#

second is availability

#

just keep in mind that if any sensor drops out, the entire sensor drops out

#

which might not be what you want

#

if you want it to always have a value, omit the availability template and just have your state as

{% set entities = (
  'sensor.ensuite_ceiling_energy',
  'sensor.ensuite_vanity_energy',
  'sensor.toilet_ceiling_energy',
  'sensor.bathroom_ceiling_energy',
  'sensor.bathroom_fan_energy',
  'sensor.underhouse_storage_energy',
  'sensor.workshop_energy',
  'sensor.toilet_fan_energy',
  'sensor.entrance_chandelier_energy',
) %}
{{ entities | map('states') | map('float', 0) | sum | round(2) }}
formal ember
#

oh cool. that makes sense if one of them goes offline

mighty ledge
#

keep in mind, you'll get jumps in your data when you restart. There's a trade off

formal ember
#

what would petro do?

mighty ledge
#

petro doesn't restart

formal ember
#

(have not had one go offline - if one goes offline they all go offline)

formal ember
mighty ledge
#

I do them once and a great while

#

and I ignore the data from that day

#

or I use an availability template

#

with the one listed above

#

all or nothing

formal ember
#

roll of the dice, flip of the coin

#

how would what you suggested fit into the sensor? is it just after state: >-?

mighty ledge
#

just replace your 2 templates with what I wrote above

#

make sure you add in the spaces for each

plain magnetBOT
formal ember
#

like so?

#

3.76 # # # # # # # # # # # # # # # # 3.65

#

thats a funny state

mighty ledge
#

are you running 2022.11?

#

calculates fine for me

#

but you need to be on 2022.11

formal ember
#

yeah i am

mighty ledge
#

then you should simply get a sum

formal ember
#

fk i know why. i commented out the old stuff, but its still picking it up!

mighty ledge
#

you can't comment out anything in templates

formal ember
#

now i know ๐Ÿ˜‰

proven fog
#

I'm trying to change the color of an icon based on the temperature of a room vs the temperature the thermostat is set to, so I can quickly see if a specific room is too hot or too cold. And was hoping you smart folks might be able to help me logic this out, because I think I might be approaching it in a sub-optimal way.

Currently doing temp_diff = (thermostat_temp) - (room_temp) and then if temp_diff is -X degrees or lower a light blue color. If it's between these temps return a darker blue color, if it's between an 'optimal' range return white, if it's too high, yellow, orange, red, etc. And that has been working great for when the AC is on. Because when you set the AC on, you want it to be that temperature.

But now that I've switched over to heat, the logic doesn't really work anymore. It's not that cold outside yet, so heat's not even running. T-stat is set to 68ยบ F so the heat kicks on when it's actually cold at night, but some rooms are floating around 72-74ยบ during the day which is great. But my sensors are showing RED because it's more than a 5ยบ temp_diff

any thoughts?

obtuse zephyr
#

Maybe have a condition check to have different ranges/thresholds based on climate mode of your thermostat

proven fog
#

Yeah, that's what I was thinking originally. Just wasn't sure if there was a more elegant solution that I hadn't thought of

solar swallow
#

I'm attempting my first template for a lovelace card, and I'm a little over my head with formating
Charley's next important date is {{ (state_attr("calendar.charley","start_time")) }} results in Charley's next important date is 2022-12-02 14:00:00 but I'd ultimately like Charley's next important date is on 12-02-2022 at 2:00pm

silent seal
inner mesa
#

{{ state_attr('automation.alarm_armed', 'last_triggered').strftime("%-m-%-d-%-Y at %-I:%M%p") }}

#

-> 11-11-2022 at 6:56AM

marble jackal
#

Grrr, I was just completing this:
{{ now().strftime('%d-%M-%Y at %I:%M %p') }}

solar swallow
#

I have a syntax error

silent seal
#

| relative_time another nice one to use

marble jackal
#

I'm on mobile, so I needed to come back here to copy and combine it

solar swallow
#

{{ (state_attr('calendar.charley','start_time')).strftime("%-m-%-d-%-Y at %-I:%M%p") }}
UndefinedError: 'str object' has no attribute 'strftime'

silent seal
#

What is the error that you get?

#

Ok, that's easy enough

#
{{ (state_attr('calendar.charley','start_time')) | as_datetime | strftime("%-m-%-d-%-Y at %-I:%M%p") }}
#

*easy enough for me

marble jackal
#

Almost:

{{ ((state_attr('calendar.charley','start_time')) | as_datetime).strftime("%-m-%-d-%-Y at %-I:%M%p") }}
#

You can't use strftime() as a filter

silent seal
#

Darn, I always forget that one

inner mesa
#

if I ever start typing a complex template on my phone and see somebody smarter than me typing, I just erase and move on ๐Ÿ™‚

solar swallow
#

okay it works! now I gotta look through the linked document and figure out what I can learn
and then, how to get that into a lovelace card

#

thanks!

silent seal
#

The markdown card will be a good helper to start with ๐Ÿ™‚

marble jackal
solar swallow
#

one persons simple is definitely my complex ๐Ÿ˜‚

inner mesa
#

anything that requires me to repeatedly switch between alpha and two different sets of symbols on my phone is "complex" ๐Ÿ™‚

marble jackal
#

Ah, right, that's true.. adding code tags is almost complex then. That backtick is hidden in a deep dungeon of the Android keyboard

inner mesa
#

it's less about the difficulty of coming up with it than the challenge in testing it and typing the thing in the first place

solar swallow
#

Thanks for everyones help
I got everything looking how I wanted

pliant elbow
#

Hi Everyone! I am looking for some help with a template sensor. For the life of me, I can't figure out why the template sensor is "unknown". I have a boiler that has an API and it exposes data about the current state of the boiler. The detailed data comes across in state attributes of the entity sensor.ibc_boiler. Here are the attributes: http://pastie.org/p/6iZ8pakEYJHGcIr04EzGv7

#

I am using template sensors to break out the attributes into their own entities. I am able to get SupplyT and ReturnT, for example, just fine however Errors and Warnings are always unknown

#

I can't quite figure out why, when in developer tools I can see the data for both is None

#

Here is my template sensor

    state: "{{ state_attr('sensor.ibc_boiler', 'Errors') }}"```
inner mesa
#

'None' is special

pliant elbow
#

Oh man....๐Ÿ˜

#

three hours of troubleshooting to find out 'None' is a reserved word

#

lol

#

Is it possible to evaluate for none and change the message in the template sensor?

inner mesa
#

Yes

pliant elbow
#

Ok cool! Thanks so much!

#

I appreciate it

inner mesa
#

{{ 'Nothing' if x is none else x }}

#

Or, better

#

{{ x|default('Nothing', True) }}

pliant elbow
#

Awesome!

inner mesa
#

Probably don't need the True

pliant elbow
#

Cool, going to add it right now

#

Thanks so much!

inner mesa
#

you do need the , True

low blaze
buoyant pine
inner mesa
#

I'm not so sure

buoyant pine
#

None is its own data type though (NoneType)

#
matt@server:~$ python3
Python 3.9.2 (default, Feb 28 2021, 17:03:44)
[GCC 10.2.1 20210110] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> type('None')
<class 'str'>
inner mesa
#

Still not sure that translates back to the state that way.

#

I'm pretty sure I've had that issue

buoyant pine
#

Interesting. To be fair, it's probably best to avoid anyway

#

I was still curious

#

But yeah, if you've had issues with it before, still probably just best to avoid

inner mesa
#

I recall that the problem was returning that as a state of a template sensor

buoyant pine
#

Errors: Nada

#

Errors: Nope

pliant elbow
#

On Template page there is this example:

  - binary_sensor:
      - name: "Has Unavailable States"
        state: "{{ states | selectattr('state', 'in', ['unavailable', 'unknown', 'none']) | list | count }}"```
#

It appears none and unknown might be the same thing so does it all resolve back to unknown?

#

not sure

inner mesa
#

so...

#

state: "None" gives a "None" state

#

state: "{{ 'None' }}" returns "unknown"

#

as does state: '{{ "None" }}'

#

So if you just use a string, you're good. If you return it from a template, it's converted into the type

buoyant pine
#

Interesting

inner mesa
#

on the other hand, state: "{{ 'none' }}" returns "none"

#

do with that what you will

tribal cedar
#

Is it possible to create sensors/binary sensors in a loop in the configuration.yaml. Instead of a sensor configuration per room, I would love to create the same sensors in a loop to reduce duplication.

heavy crown
pliant elbow
#

Now I'm good to go!

#

Thanks again!

spare lichen
#

{% if states['sensor.anyfanon'].attributes.[variables.attri] > 0 %} show {% else %} hide {% endif %}

what I'm doing wrong ?+

inner mesa
#

you have an extra "."

#

compare: states['sensor.anyfanon'] to attributes.[variables.attri]

#

that whole construct isn't ideal

#

{{ iif(state_attr('sensor.anyfanon', variables.attri) > 0, 'show', 'hide') }}

spare lichen
#

gettin error

#

expected ',' or '}', but got '<scalar>' in

inner mesa
#

keep looking, I guess. works for me

spare lichen
#

{% if state_attr('sensor.anyfanon', '[variables.areazone]') > 0 %}
show
{% else %}
hide
{% endif %}

still can't get it to work

tribal cedar
# heavy crown Hi, you entered this too in the forum and I 'guess' I know what you want but was...

I have many sensors and binary sensors for things like detection if motion was recently detected in a certain room, performing of counts of certain actions per minute in various rooms. Theres a sensor for each room which runs a certain piece of logic, with time/date comparisons inside and other checks. The only difference between the sensors is the name and an entity id checked inside. So I want to automatically generate sensors, with the contents of the template for each sensor being parameterized.

inner mesa
#

Good luck

spare lichen
#

What you gave didnt work
So tried something else

marble jackal
#

Did Rob have square brackets in the state_attr()

spare lichen
#

I tried also without square brackets

inner mesa
#

Random musings

spare lichen
#

{% if state_attr('sensor.anyfanon', variables.areazone) > 0 %}
show
{% else %}
hide
{% endif %}

marble jackal
#

Are you sure you don't need areazone instead of variables.areazone?

#

If you defined them under variables: you don't need it

#

Unless you did

variables:
  variables:
    areazone: "foo"
spare lichen
#

Variables:
areazone: "pczone"

inner mesa
tribal cedar
#

Can templates be used in device select_option blocks, it seems not, unless I'm doing it wrong, ie the following string is being passed literally to my device, not the value of the rendered block of template.

device_id: a1f2.....
domain: select
entity_id: select.harmony_hub_activities
type: select_option
option: "{{ states('input_text.desired_harmony_option') }}"

spare lichen
spare lichen
#

{% if state_attr('sensor.anyfanon', areazone) > 0 %}
show
{% else %}
hide
{% endif %}
still nothing

marble jackal
hybrid gale
#

there is a template concept of integration_entities(arg) where you pass in an integration 'key' to get a list of items within it

tribal cedar
#

Thank you @marble jackal !

hybrid gale
#

but how do you iterate on integrations?

plain magnetBOT
#

Sadly we're not mind readers (any more anyway, not after the last time we tried). Please share the YAML and any errors so we can see what you've done.

marble jackal
plain magnetBOT
#

Please use a code share site to share code or logs, for example:

Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.

marble jackal
#

I meant that bot message

arctic sorrel
hybrid gale
#

not 'the'

#

all of the running ones

arctic sorrel
#

You want to iterate over every integration in your system, without knowing what they are?

spare lichen
hybrid gale
#

I mean, the system knows

#

why should I copy paste data that's just going to fall out of date

plain magnetBOT
#

The XY problem is asking about your attempted solution rather than your actual problem.

arctic sorrel
#

you may want to explain your goal here, it'll help people help you

hybrid gale
#

I want to assign area on entities based on other aspects of them... names or inheretence tree or things like that

spare lichen
hybrid gale
#

I mean, at the core of this

inner mesa
#

You can't do that programmatically

hybrid gale
#

dang

#

cause there's no way to bulk set area in the ui either

#

you have to do it one thing at a time

#

so if I have large numbers it's... miserable

marble jackal
acoustic arch
#

Hey. I have a big list of ping entities of iot devices, all ending ttheir name with _status. How can i template them as trigger going to off state, in a way so i can notify my mobile the one that went offline?

#

else i have to select them all and keep track of them whenever i make a new one

#

like this but then smart:

entity_id:
  - binary_sensor.camera_achtertuin_status
  - binary_sensor.otgw_status
to: "off"
for:
  hours: 0
  minutes: 10
  seconds: 0```
plain magnetBOT
lime shell
#

On the right channel this time ๐Ÿ˜€
Hello, Can anyone help me out with this? i need to create a new "sensor" that shows the difference between 2 sensors, this is what i got but something is wrong.

template:

  • sensor:
    • name: "Solar Total Energy"
      unit_of_measurement: "KWh"
      state: >- {{ states('sensor.solar_energy_total_energy') - ('sensor.house_energy_total_energy') }}
arctic sorrel
#
        state: "{{ states('sensor.solar_energy_total_energy')|float(0) - states('sensor.house_energy_total_energy')|float(0) }}"
#

you forgot the second states ๐Ÿ˜‰

lime shell
#

so you need states for every sensor right?

bronze dune
fresh kettle
#

Hi Team, This may be a weird question but going to ask anyway.
I have a sensor the has a value anything between 1 and 100.
I am trying to set a helper to the closes lower "10" of the number of the sensor.
eg. if the sensor is 18 then I want to set my helper to 10. if its 55 the I want to set it to 50.
I looked at "round" and a few other but cant get it to give me the rounded number to 10.
Can anyone of help give me an idea on how to get this working please?

obsidian lintel
#
  {% for person in ns.persons %}

    <img src="/local/{{ ns.persons[{{loop.index-1}}] }}.jpg" width="50%">
    
  {% endfor %}

How do i put a loop index inside my namespace?

#
  {% for person in ns.persons %}

    <img src="/local/{{ ns.persons[0] }}.jpg" width="50%">
    
  {% endfor %}

This works but I want the for loop to iterate through my namespace indexes as I got different images

marble jackal
#

You are nesting templates

obsidian lintel
#

Oh yeah, i just realised

#

Whats the way to go about it

marble jackal
#

For the first one you should remove the curly brackets around loop.index -1

obsidian lintel
#

Oh wow

#

That worked nicely

#

Thanks @marble jackal !

bronze dune
marble jackal
#

Your template is really overcomplicated

marble jackal
fresh kettle
fickle kettle
#

I was about to help, but looks like you've got it sorted ๐Ÿ™‚

#

@lime shell did someone help you yet?

lime shell
#

Yes it's working

fickle kettle
#

Excellent

bronze dune
#

@marble jackal Firstly, extreme thank you - I'll study this and improve how I make things.
Question: The |unique throws an error in the template? <generator object do_unique at 0x7f7ca4e8f0>

fickle kettle
#

Can you post you template code somewhere so we can look? Probably unique is getting a None or something. Would need to see full error

bronze dune
fickle kettle
#

sorry I have to go to my grandkid birthday now, no time to help. Maybe when I get back in ~6 hours

#

try breaking down that final expression, and printing the bits. I bet one is None or something like that

#

afk

vestal aspen
#

can i use a helper value in a restcall?

#

input_text.chighlight

inner mesa
#

Lots of examples right there

fickle kettle
#

I'm back. Did you get solution @marble jackal ?

marble jackal
#

{{ (lightsOn + lightsOff) | unique | list }} was what it should have been

bronze dune
#

Ahh.. ok thanks! That works

fickle kettle
#

Good good

crimson cave
#

Has anyone got a good tip on how to create reusable calculation modules for use in templates ?

I have some calculations that i need to do in multiple places but based on different input values and i would very much like to create these as "functions" that i can use in any template that needs that calculation, so that i don't have to include the full template code in every place i want to perform the calculation. This makes things very complex to maintain.

I have seen suggestion to use yaml anchors on reuable templates code but i cannot see a way to parse one or more parameters to a piece of anchored template code.

marble jackal
#

You can use trigger based template sensor and add the input as trigger variabeles

untold swift
#

Hi,

Anyone give me some pointers on making an entity from an existing entity?

I'm trying to make a new entity from media_player.spotify_home_assistant

The code I have is below, but I'm unsure what platform I would need..

#

platform: spotify_song: friendly_name: "Spotify Song" value_template: "{{ state_attr('media_player.spotify_home_assistant', 'media_title') }}"

left canopy
#

Hello Everyone. I want to build a card for all my rooms. Is there a way to template this ro will i have to create individual yamls for each?

marble jackal
untold swift
#

yeah, indent is due to Discord

untold swift
#

I literally just figured it out about 3 seconds before the bing noise XD

#

Thank you though

#

What would be the difference with the newer format? The only things I can find is older code, so updating to latest format would be advantagious

#

oh... I think I understand this!

marble jackal
#

Newer code supports state_class and self referencing using this

untold swift
#

I think I may have cracked it! Let me test

#

maybe not...

#

maybe I'm just a complete moron XD

#

it would be helpful if I referenced the templates files and folder correctly!

#

... and that works gloriously with the new format

#

thank you

#

is there a list of variables I can see for an entity? I have media_artist and media_track, but can I also pull duration, album art etc?

desert tangle
#

Is there something wrong with this:

#

Or why it does not show "compressor" image on that picture element?

inner mesa
marble jackal
#

But most attributes for a media player are only available while playing something

untold swift
#

Thank you

low blaze
#

is there a function that could show a delta of a sensors value over a period of time and be "live"? for example I have a sensor that reports every 10 seconds, is it possible to have a 6hr % change sensor?

marble jackal
#

Templates are only in live data

#

But you could use an SQL sensor to get the value from six hours ago out of the database

wary moon
#

Hello, I am trying to write a template that sifts thorugh states.sensor and in the end sorts by state, something like {{ states.sensor | filter1 | filter2 | sort('state') }}. The problem is that homeassistant stores the values as strings, and lexicographical order & numerical order are not the same thing. In my case, the state is a float, and I would like to convert it before sorting happens. I could not find any way to do that in jinja, nor it seems to be possible through homeassistant in some way. Is there any way to solve this problem?

#

For some context, the result of this is needed within a notify call, to advise the user about what power sensor is reporting the highest consumption.

inner mesa
#

I would like to convert it before sorting happens.
|map('float')

wary moon
#

Yep the problem is that map('float') does not work on the list of entities. I can extract the state but then I lose the friendly_name, which I want to keep instead - the final idea is to produce a notification like "Currently the $friendly_name is consuming $state W" where both the name and the consumption are extracted from states.sensor

#

Ideally I would need something like map('float', attribute='state') if that makes sense

marble jackal
#

@wary moon You need to use a for loop with a namespace to create a list with the thing you want (the friendly name for example) and the state as a float, and then use that to sort it. At least, that is what I would do

#
{%- set ns = namespace(sort = []) %}
{%- for item in states.sensor | selectattr('state', 'is_number') %}
  {%- set ns.sort = ns.sort + [ dict(name=item.name, state=item.state | float) ] %}
{%- endfor %}
{{ ns.sort | sort(attribute='state') }}
acoustic arch
#

{{ states.binary_sensor|map(attribute='entity_id') |list }} How can i select all entities ending with a certain string? _status in my case

silent seal
#

selectattr, though I'm not sure it works with a regex.

acoustic arch
#

is there another way to select only a couple based on some parameter?

#

i have ping sensors for iot devices. I dont want to keep track of the list but scoop them all up in one smart template

marble jackal
#

| selectattr('entity_id', 'search', '._status$')

acoustic arch
#

ooooooooooh fancy!

#

ill test it straight away

silent seal
acoustic arch
#

my syntax is ehhhh broken.

#

as per usual ๐Ÿ˜œ

#

i get ALL info on the ping sensors not just the entity name to use in as a trigger

silent seal
#

You'll need to map the entity id ๐Ÿ™‚

marble jackal
#

You removed the map()?

acoustic arch
#

ye didnt work

#

{{ states.binary_sensor| selectattr('entity_id', 'search', '._status$') | list }}

this gives me ALL info

marble jackal
#

Yes, that's because you removed the map()

acoustic arch
#

nvm... got it lol

#

{{ states.binary_sensor| selectattr('entity_id', 'search', '._status$')| map(attribute='entity_id') | list }}

#

๐Ÿ™‚

#

thx! saves me keeping track of all sensors

#

well.... im not out of the woods yet. i need a template trigger: If any of these mapped entities go to off

silent seal
#

Well, that's a bit trickier, because the state trigger doesn't let you input a template.

acoustic arch
#

{{ states.binary_sensor | selectattr('entity_id', 'search', '._status$') | map(attribute='entity_id') == 'off' }}

i cooked up this

#

it shows false now. which is correct, but yet to pull one ping device offline

silent seal
#

The problem is you're checking if the list of entity_ids equals off.

#

So if [sensor.1, sensor.2] == 'off'

acoustic arch
#

so you want to fill the state trigger a full array as entities

#

then you can even pass the bad one to notify

silent seal
#

No, you can't do that, the state trigger doesn't take templates

acoustic arch
#

ah gotcha

#

a for each loop?

#

for each x in y check off

silent seal
#
{{ states.binary_sensor | selectattr('entity_id', 'search', '._status$') | selectattr('state', 'eq', 'off') | map(attribute='entity_id') | list | count > 0 }}
#

That's a guess, I'm not sure that'll work. Because if you have one offline device you won't get another trigger

acoustic arch
#

that gives a trigger

#

thats not a problem cuz ill go and find it straight away. But the bad entity is no known

silent seal
#

But, if you use a condition instead of the > 0, and save the count of offline devices to an input_number, or something I'm sure you can manage it

#

But what are you trying to accomplish here?

acoustic arch
#

its fancy to get a notify of it but not really needed

#

notify me of the entity name going offline

#

like bad wifi or whatever

silent seal
#

But why?
If something is offline due to bad wifi, then it will be "unavailable", not "off"

#

And if the network is down, the notify won't work

acoustic arch
#

the ping binary sensor will be off though

#

i have cameras as well

#

not integrated into HA

marble jackal
#

Like Rosemary said, you will only get a trigger if it goes from 0 to 1, but not if a second device fails

acoustic arch
#

thats better then my girlfriend yelling this or that isnt working ๐Ÿ™‚

marble jackal
#

you can use the template you had to get the entity_id of the device which caused it

#

replace entity_id with name to get the friendly name

#

and jou can use join(', ') instead of list to get a string instead of a list

silent seal
#

I'd do the join, maybe sort the list first to be sure, and save it to an input text.

#

Then you can compare it to the input text for changes.

marble jackal
#

If you want a trigger for the second/third/etc device as well, I would createa a template sensor with a count of the devices which are offline, and a list of the devices which are offline in an attribute

#

then trigger on a state change of that template sensor, check if the value increased in a condition

acoustic arch
#

hahaha its becoming wayyyy overkill ๐Ÿ™‚ i like that.

silent seal
#

Ooh, much better idea

marble jackal
#

an compare the new value of the attribute with the old to see which one caused it

acoustic arch
#

all stuff is working pretty well with 4 APs in the house, but i like it

silent seal
#

Of course, if one device goes offline as another comes online then you might not get a trigger ๐Ÿ˜›

marble jackal
#

it has to be within one second, as states[domain] templates are rendered once per second

acoustic arch
#

is the outgoing ping in sych for all

#

?

#

i can do differenct intervals for all ping sensors

#

120 sec 118sec 116 sec etc

marble jackal
#

if you would put them in a group (which you can do dynamically using group.set) and use expand on the group, you have instant updates

acoustic arch
#

its getting over my head now.

#

ill digest this first ๐Ÿ™‚

marble jackal
#

or, if they are the same 4 devices always, just add them in a binary_sensor group

acoustic arch
#

its like 20 wifi iots

#

removing and adding as i please/is needed

#

hence the ping binary sensor so i only need to keep track of that yaml file

#

and a trigger with entities ending with _status

#

that was my novice idea anyway ๐Ÿคท๐Ÿผโ€โ™‚๏ธ

marble jackal
#

Well, what I would do:

acoustic arch
#

o dear.... here it comes

#

trash previous, do this:

marble jackal
#
  • on startup of HA, and reload of ping sensors, create a group with all these binary sensors
  • create a template sensor with the count of the group members which are off and the names in an attribute
  • use that sensor for the automation
acoustic arch
#

thank you for your effort! both of you. Im going to re-read this tomorrow and hopefully i can cook something up

#

๐Ÿ™Œ๐Ÿผ

dry narwhal
#

Hello everyone,
I am trying to create a list of sensors matching two criterias. One is part of the name and one is the area.
I cannot figure out the area filtering.

#
{{ area_entities(states('input_select.dropdown_areas')) }}

{{ states.sensor|selectattr('object_id', 'match', 'xiaomi_humidity')|map(attribute='name')|list }}
#

The first returns all entities in the area (but as entity_id rather than the wanted friendly_name)

#

The second gives me the result I want but not filtered for area

silent seal
#
{% set entity_list = area_entities(states('input_select.dropdown_areas')) %}

{{ states.sensor | selectattr('object_id', 'match', 'xiaomi_humidity') | selectattr('entity_id', 'in', entity_list) |map(attribute='name') | list }}
#

Or something like that. I'm guesstimating as I'm on mobile.

dry narwhal
#

Thank you! That works perfectly!
I kept trying an integrated one liner version and kept failing ๐Ÿ™ˆ

#

And then merged

{{ states.sensor | selectattr('object_id', 'match', 'xiaomi_humidity') | selectattr('entity_id', 'in', area_entities(states('input_select.dropdown_areas'))) |map(attribute='name') | list }}
silent seal
#
{{ area_entities(states('input_select.dropdown_areas')) | selectattr('domain', 'eq', 'sensor') | selectattr('object_id', 'match', 'xiaomi_humidity') | selectattr('entity_id', 'in', entity_list) |map(attribute='name') | list }}

Would have been my guess, but that works too

slow vine
#

I can't seem to figure out how to match foo "OR" bar in i.e. {%- if 'espressif' OR 'ESPHome' in manufacturer -%} Is it possible?

fickle kettle
#

You'd need to do: if 'espressif' in manufacturer or 'ESPHome' in manufacturer

#

Or use set-logic

slow vine
#

don't know what set-logic is yet ๐Ÿ™‚ but this worked {%- if 'ESPHome' in manufacturer or 'espressif' in manufacturer -%}

inner mesa
#

{% if manufactuer in ['ESPHome', 'espressif'] %}

fickle kettle
#

Or you could do:

if {'ESPHome', 'espressif'} & manufacturer

inner mesa
#

hmm

#

no idea what that's about

fickle kettle
#

is manufacturer a list or a string?

#

if it's a string, use "in" like rob said

slow vine
#

its a string.

fickle kettle
#

OK use what rob wrote. I assumed it was a list/set because you were using "in" on it

atomic blade
#

I'm trying to filter for entities that don't have an "alarms" attribute OR a "timers" attribute. Of course I can't just add one before or after the other since then they would already have been excluded. This is what I have to filter one of them, but how would I do filter for one or the other?

...
|rejectattr('attributes.alarms', 'undefined')
...
inner mesa
#

I don't see why you can't just use two |rejectattr()

atomic blade
#

Say I have a bunch of entities that have one of the following: only an alarms attribute, only a timers attribute, or neither. If I filter for entities with the alarms attribute then filter for entities with the timers attribute, those that actually have the timers attribute will already have been rejected by the first filter because they don't have an alarms attribute.

inner mesa
#

Perhaps I'm missing something, but when you say "don't have an 'alarms' or 'timers' attribute", it sounds like you're looking for entities that have neither

#

so reject both attributes

mighty ledge
#

filter with timers attributes, reject alarms. If you're trying to remove both, just reject both in any order.

thorny snow
#

I have a helper, which counts the impulses of my gasmeter.

I also have a template that represents the total gss consumption in mยณ.

I want to have ab other template, that calulates the Gas consumption per h, per day, per week.

How can I access the timestamps to do this.

mighty ledge
#

or use the energy tab

#

if you don't want entities

thorny snow
#

thanks!
for me to learn:
If I want fo aggregate values of a timeserie, can this be expressed in a template too?

silent seal
#

I'd suggest for anything like that you should look at InfluxDB (and optionally Grafana for pretty charts)

mighty ledge
#

i.e. there's no point to investigate it because you can't get to it.

thorny snow
#

Thanks.

#

Iยดll try this out

#

An other issue:
I have wrong data for the helper, on one day in the past, where I setted it up.

This disturbse now all statistics.

How can I get rid of the helpers historical data for one day in the past.

atomic blade
atomic blade
#

I'm not sure how else I can put it

mighty ledge
#

You said rejectโ€ฆ

marble jackal
#

so you want all enties which:

  • don't have an alarm attribute
  • do have a timer attribute
atomic blade
marble jackal
#

create 2 lists and combine them

mighty ledge
atomic blade
mighty ledge
#

Yes and it had rejectโ€ฆโ€ฆโ€ฆโ€ฆโ€ฆ..

atomic blade
#

But it was confusing how I was using a double negative, I agree

#

Isn't rejecting undefined the same as selecting it being present?

marble jackal
#
{% set no_alarms = states.sensor | selectattr('attributes.alarms', 'undefined') | list %}
{% set timer = states.sensor | selectattr('attributes.timer', 'defined') | list %}
{{ no_alarm + timer }}
atomic blade
#

I was looking for a solution in a single filter though

marble jackal
#

that's not possible for the reason you already stated, you filter out entities you need

atomic blade
#

Well I didn't think it was possible, but also I'm sure there are better templaters in here

atomic blade
#

I wanted it with one or the other

marble jackal
#

whatever, your descriptions were very unclear

atomic blade
#

Rereading my first sentence I think it could have been better:

I'm trying to filter for entities that don't have an "alarms" attribute OR a "timers" attribute

#

I should have said "out" instead of "for"

#

Also didn't specify if the "don't" applies to the second clause

mighty ledge
#

if you're trying to filter them out, then that's sipmly reject attr

#

this is what you aren't understanding

#

so you have a fundamental incorrect thinking on what filter means.

#

when you filter something out, you remove it

#

meaning you'd be left with all sensors that DO NOT HAVE alarms or timers

atomic blade
#

Yes, and at the time I had double negative logic, so I was looking to filter out what I wasn't looking for

mighty ledge
#

not "I only want a list with alarms or timers"

#

if you want to filter out entities then you just use rejectattr, i feel like we are going in circles here

atomic blade
#
{% set no_alarms = states.sensor | selectattr('attributes.alarms', 'defined') | list %}
{% set timer = states.sensor | selectattr('attributes.timer', 'defined') | list %}
{{ no_alarm + timer }}
#

This was the solution

mighty ledge
#

AND THATS NOT FILTERING OUT

marble jackal
#

that's selecting ๐Ÿ™‚

mighty ledge
#

ffs

#

FILTERING OUT IS EVERYTHING BUT THAT LIST

atomic blade
#

When you say "I want this" in a filter you're also saying you don't want everything else

#

Filtering is the |

mighty ledge
#

"I want to filter down to a list of alarms or timers"

silent seal
#

That's using a filter function

#

filtering out would be rejectattr

atomic blade
mighty ledge
#

right, but you've reworded it wrongly every time you've said it

atomic blade
#

I was using the word filter in the technical aspect like Rosemary said

silent seal
#

You need to be clear if you mean a filter function or filtering a list of somethings.

atomic blade
#

Well my example had the |

silent seal
#

It's often best to describe your problem as simply as you can:

I want to get a list of the sensors which have an attribute "alarms", or an attribute "timer"

atomic blade
#

I agree I didn't word it very well initially. Fes was able to figure it out without too much fuss though

silent seal
#

And then you can include your example after that, but the simple explanation at the start is really critical ๐Ÿ™‚

marble jackal
atomic blade
#

lol true

silent seal
#

Incorrectly named variables are one of the banes of my existence ๐Ÿ˜›

atomic blade
#

That's why I try to do everything in a single filter, don't need variables ๐Ÿ™‚

silent seal
#

Oneliners sound good, but it makes re-using things harder.

#

It's a script kiddy approach usually.

#

(I say that as a former script kiddy ๐Ÿ˜‰)

atomic blade
#

Maybe I should have given a code example of how to accomplish it

...
.filter(foo -> foo.attributes.includes('timers') || foo.attributes.includes('alarms')
...
#

Haha well I'm certainly not a script kiddy. They just read easier for me. You're just applying rules one step at a time

mighty ledge
#
{{ states.sensor | rejectattr('entity_id', 'in', states.sensor | rejectattr('attributes.timers', 'defined') | rejectattr('attributes.alarms', 'defined') | map(attribute='entity_id') | list) | list }}
#

there's your oneliner

marble jackal
#

Aaah, that looks easy on the eye!

atomic blade
#

Haha tbf I was kidding about always using only filters. I think with some formatting that would be easier to read though

#

That's the first thing I started doing when he pasted that

atomic blade
#

Also since in most cases I prefer filters, I try to figure it out that way first because it helps me get better with them

mighty ledge
#

it works perfectly fine if your goal is to get a list of entities that have alarms or timers attributes

atomic blade
#

Let me take a look over it again. I think I understood what you had there but maybe not.

Here's an alternate solution sort of along the lines of what you had:
Here's an alternate solution

{{
  states.sensor
  | selectattr('entity_id', 'in', 
      states.sensor | selectattr('attributes.alarms', 'defined') | map(attribute='entity_id') | list
      +
      states.sensor | selectattr('attributes.timers', 'defined') | map(attribute='entity_id') | list
  ) 
  | map(attribute='entity_id')
  | list
}}
mighty ledge
#

yep, but you're iterating the state machine 3 times vs 2

atomic blade
#

True

silent seal
#

Much less efficient, and long term that adds up

atomic blade
#

Ok actually now I'm getting correct results when I run what you had. Weird

#

Ah ok I see, you're inner filter is getting a list of everything excluding entities that have either attribute, then you're excluding that from the total list to get the inverse

#

It still should be possible to iterating it once though...

mighty ledge
#

it'll never be possible, these aren't lambda functions

atomic blade
#

How do they differ?

#

They seem the same fundamentally. You're telling it to do some operation on each element in the list

mighty ledge
#

select, selectattr, reject, and rejectattr only allow 1 attribute at a time. That's a limitation of those BUILT-IN jinja functions. You can't get around it.

atomic blade
#

Well they allow one argument, specifically right?

mighty ledge
#

those generators work on 1 item in the list at a time, and selectattr/rejectattr require 1 attribute as an argument.

atomic blade
#

Couldn't that one attribute be the attributes list? Just spitballing

mighty ledge
#

no, it's a BUILT-IN jinja filter

atomic blade
#

Oh sorry, yeah I mean for select/reject

mighty ledge
#

we would need a new test that accepts a list

#

and even then, you can't check for defined

atomic blade
#

Well you could do another in() on that list to see if the attribute is there

#

But yes you're right about the test

mighty ledge
#

no you couldn't unless you made the new test accept tests

atomic blade
#

Ok I see

#

I'm still not sure jinja template filters are fundamentally different from lambas though. It's just that you have a limited number of lambda functions you can call

#

I think that's why it's a bit difficult for me to see the limitations

mighty ledge
#

they are different as in they are constrained by what you can use. It's not a developed set of rules like lambdas where you can map things and retain the original object.

atomic blade
#

I understand and agree with the first sentence, not sure about the second. But my experience with this is more in java (streams) than python

#

But I assume the underlying concepts are still the same. In a stream you run into this same problem where you only have what made it past the last map() or filter()

#

In jinja it seems like the select and rejects are like filters, but like you said they're just constrained

#

I mean like I get it, just saying that fundamentally they are the same so it's kinda hard to see where the limits are

#

Like saying, write some program, but you can't use the letter 'i' lol

mighty ledge
#

well, you can expect the proper order of operation, but it's order of operation is arguments first, then function/filter/tests. Where lambdas execute the code with their own set of rules for order of operation

#

lambdas you're also defining a function to execute at that moment in time

#

where as jinja, everything is pre-defined

#

it's really apples and oranges.

sacred sparrow
#

Is it possible to make a icon a template like: {{ mdi:light }} - its for a lovelace card

inner mesa
#

Depends on the card.

#

You would need to surround that in quotes, regardless

plain magnetBOT
merry delta
#

Did I post my code or question incorrectly? I'm not good on dicord

#

Hiw do I post a template that's above 15 lines and ask for help? I was told to goto discord for help? Sorry I am old and dumb

inner mesa
#

is the "if" statement in value_template working as you expect?

#

I don't know what phu: is, but I'm guessing some third-party icon library

#

I suggest putting the template in devtools -> Templates, seeing if it evaluates as you expect there, and debugging

#

there's nothing wrong with the syntax

merry delta
#

The templates work in developer except I don't think it can debug the icons, and yes it's 3rd party icons but I also have tried with mdi

inner mesa
#

It only matters that it outputs the correct string

merry delta
#

Well it's only putting out the else string I dunno why

inner mesa
#

Then it's not working ๐Ÿ™‚

#

The first and second templates are identical, so are both working or not?

#

Check the states in devtools -> States

merry delta
#

It very well could be a problem with these binary_sensors. They say clear even when I am triggering them. So that what I need to figure out.