Generalizing a template for several entities

Dear community,

Suppose I have written a template like this:

  - platform: template
        friendly_name: "Samsung Galaxy"
        value_template: "{{ state_attr('device_tracker.google_maps_123', 'battery_level') | round | default('?') }}"
        friendly_name: "iPhone"
        value_template: "{{ state_attr('device_tracker.google_maps_987', 'battery_level') | round | default('?') }}"

however I would like to generalize this template for all entities like phone_*_battery, however I don’t know how to pass/substitute the value device_tracker.google_maps_XXX:

      value_template: "{{ state_attr( ??what_comes_here?? , 'battery_level') | round | default('?') }}"

My idea was to define an attribute e.g. entity_reference: "device_tracker.google_maps_XXX" in sensors definition but how to access current / this attributes list from the template?

Many thanks!

You can’t generalize templates because templates need an entity_id to create a listener. Without that listener, they won’t update.

EDIT: Also, customize is for customizing. Adding value_template to customize will just add a value_template attribute with the template as a string. You can’t add templates to your configuration outside the specific fields that accept templates. As a whole, customize does not allow templates.

That’s pity. Actually this is only a matter of when the templates are processed. At the end the glob is resolved to a sets of entities, each having the entity_id.
Anyway, what’s the way out? Copy hudge templates from one entity to another?

Pretty much. You can use the template editor to do the work for you.

{% for s in states.device_tracker %}
{% if 'google_maps_' in s.object_id %}
    value_template: {{ "{{ state_attr('{}', 'battery_level') | round | default('?') }}".format(s.entity_id) }}
{% endif %}
{% endfor %}

Another option is to use something like AppDaemon to create the entities. It can loop through your devices (device_tracker or otherwise) and create/update entities as they change, just like a Template Sensor does.

Yep, I do what @swiftlyfalling does. But the learning curve is steep with appdaemon if you aren’t familiar with python.