if using custom-ui, and not a template sensor, this works:
sensor.tester_state:
# icon: mdi:test-tube
templates:
icon: >
if (state === 'on') return 'mdi:test-tube';
return 'mdi:test-tube-off';
icon_color: >
if (state === 'on') return 'rgb(251, 210, 41)';
return 'rgb(54, 95, 140)';
if a template sensor, this does it:
part_of_day:
friendly_name: 'Part of Day'
value_template: >
{% if now().hour in range(0, 6) %}
Midnight
{% elif now().hour in range(6, 12) %}
Morning
{% elif now().hour in range(12, 18) %}
Afternoon
{% else %}
Evening
{% endif %}
icon_template: >
{% if now().hour in range(0, 6) %}
mdi:weather-night
{% elif now().hour in range(6, 12) %}
mdi:weather-sunset-up
{% elif now().hour in range(12, 18) %}
mdi:weather-sunny
{% else %}
mdi:weather-sunset-down
{% endif %}
or
day_night:
friendly_name: 'Day/Night'
value_template: >
{% if is_state('sun.sun', 'above_horizon') %}
Day
{% else %}
Night
{% endif %}
entity_picture_template: >
{% if is_state('sun.sun', 'above_horizon') %}
/local/weather/day.png
{% else %}
/local/weather/night.png
{% endif %}
also, customize_glob certainly has this possibility:
sensor.*_motion_sensor_temperature:
templates:
icon_color: >
if (state < -5) return 'rgb(30, 255, 255)';
if (state < 0) return 'rgb(30, 144, 255)';
if (state < 10) return 'rgb(255, 255, 0)';
if (state < 15) return 'rgb(255, 211, 30)';
if (state < 20) return 'rgb(0, 128, 0)';
if (state < 25) return 'rgb(255, 165, 0)';
if (state < 30) return 'rgb(255, 0, 0)';
if (state < 35) return 'rgb(85, 0, 0)';
return 'rgb(47, 0, 0)';
device_tracker.imac_*:
templates:
theme: >
if (state === 'home') return 'green';
return 'grey';
_stateDisplay: >
if (state === 'home') return 'On';
return 'Off';
etcetc.