Why won't truncate work on sensor.domains_in_use

HI,

using this sensor:

          {%- for d in states | groupby('domain') %}
            {%- if loop.first %}
            {% endif %} {{d[0]}}
          {%- endfor %}

works only if the count of characters is less than 255. this is discussed elsewhere, and I use a python script now to have all domains listed as attributes.

still Ive tried another option, to truncate the outcome, so to be less that 255, as follows:

          {%- for d in states | groupby('domain') %}
            {%- if loop.first %}
            {% endif %} {{d[0]|truncate(255,True)}}
          {%- endfor %}

using the above 2 templates in dev-template makes no difference, and is doesn’t in the frontend either…
this truncates all domains (using a lower number of course, left 255 in for the full list truncation), instead of the whole state of the sensor. how would I need to set it to simply cut of the end of the list, using 255?

thanks for having a look.


using truncate(7,true):

You are truncating the individual elements and not the whole string.

Try something like this:

{% set myvariable %}
{%- for d in states | groupby('domain') %}
            {%- if loop.first %}
            {% endif %} {{d[0]}}
          {%- endfor %}
{% endset %}
{{myvariable|truncate(255,True)}}

I don’t think that is legal Jinja.

You could do this:

          {% set ns = namespace(domains=[]) %}
          {% for d in states | groupby('domain') %}
            {% set ns.domains = ns.domains + [d[0]] %}
          {% endfor %}
          {{ ns.domains | join(' ') | truncate(255, true) }}

That doesn’t appear to work. I don’t believe the version of jinja being used by homeassistant allows this.
Whilst a bit hacky my solution does work.

Edit: CAVEAT - just realised I’m testing this on a pretty old version of HomeAssistant so my above comment may be gibberish. Apologies if that is the case!

No problem. I did test it (on 0.95.1) before posting.

thanks! that works beautifully. And offers another option was looking for:

{% set ns = namespace(domains=[]) %}
          {% for d in states | groupby('domain') %}
            {% set ns.domains = ns.domains + [d[0]] %}
          {% endfor %}
          {{ ns.domains | join(' ') | replace('input','inp')|truncate(255,true) }}

use the namespace only in 1 template before, so not so familiar with it yet. have to lookup some documentation in that.
Much obliged, thanks Phil (and Andrew) for helping out.

Using this now in the setup:

      domains_in_use:
        friendly_name_template: >
          Domains in use: {{ states|groupby('domain')|count }}
        value_template: >
          {% set ns = namespace(domains=[]) %}
          {% for d in states | groupby('domain') %}
            {% set ns.domains = ns.domains + [d[0]] %}
          {% endfor %}
          {% set list = ns.domains | join(' ') %}
            {{list if list|count < 255 else
              list|replace('input','inp')|truncate(255,true) }}