I’m looking to have a template sensor that contains, in an attribute, a list of mappings. Here’s what I have so far:
sensor:
- platform: template
sensors:
test:
value_template: "on"
entity_id:
- sensor.time
attribute_templates:
data: >
{%- set test1 = {
"key1" : "value1",
"key2" : "value2",
"key3" : "value3",
"key4" : "value4",
"key5" : "value5"
}
-%}
{%- set test2 = {
"key1" : "value6",
"key2" : "value7",
"key3" : "value8",
"key4" : "value9",
"key5" : "value0"
}
-%}
{{ [test1,test2] }}
When I put this in dev tools, I get the desired result. I can tell that it’s a list at that point, because if I write [test1,test2][0]
I get the first mapping. But when I create a sensor with the above definition, the attribute becomes a string, so when I write state_attr('sensor.test','data')[0]
I get [
.
Further explanation, to avoid the XY problem…
I’m using the plex_recently_added integration to pull recently added media from Plex, and then list card to display the entries in Lovelace. I’m trying to create this template sensor so that I can reformat and rearrange things in a way I like, e.g. having “$showtitle $episode - $episodetitle” in a title field, and arranging things so that there’s always 2 movies and 2 episodes in the list.
Here’s that template sensor (similarly broken):
- platform: template
sensors:
plex_recently_added_parsed:
value_template: >-
{{ states('sensor.plex_recently_added_movies') }}
attribute_templates:
data: >-
{%- set titles = namespace(entries=[]) %}
{% for media in state_attr('sensor.plex_recently_added_movies','data') %}
{% if media.title %}
{% set entry = {
"title" : media.title,
"poster" : media.poster,
"added" : media.airdate,
"released" : media.aired,
"type" : "movie"
}
%}
{% set titles.entries = titles.entries + [entry] %}
{% endif %}
{% endfor %}
{% set episodes = namespace(entries=[]) %}
{% for media in state_attr('sensor.plex_recently_added_episodes','data') %}
{% if media.title %}
{% set entry = {
"title" : media.title + " " + media.number + ": " + media.episode,
"poster" : media.poster,
"added" : media.airdate,
"released" : media.aired,
"type" : "show"
}
%}
{% set titles.entries = titles.entries + [entry] %}
{% endif %}
{% endfor %}
{{ titles.entries }}
And a couple of screenshots for clarity:
What I want:
What I get:
Thanks!