Extract information from event context data in a template

I’m trying to pull the user_id from an event when a tag is scanned but I’ve hit a wall. Using the event listener when a tag is scanned I see:

event_type: tag_scanned
data:
  tag_id: ****
  name: Something
  device_id: 4aec****da10
origin: LOCAL
time_fired: "2025-03-05T22:44:02.894071+00:00"
context:
  id: 01JNM7*****RYPKP
  parent_id: null
  user_id: d1798e***e0ef80d

Getting information from the “data” section is doable, but is it possible to extract from the “context” section using a template?

{{ trigger.event.data.tag_id }}

gives the correct tag_id but

{{ trigger.event.context.user_id }}

doesn’t return the user_id. How do I do this?

I think it’s {{ this.context.user_id }}

https://www.home-assistant.io/docs/automation/templating/#available-this-data

as in trigger.context.user_id ?

I’m trying to use this automation:

target:
  entity_id: >
    {% set user_id = trigger.context.user_id %} input_text.last_scanned_user_{{
    user_id | replace('.', '_') }}
data:
  value: |
    {{ trigger.context.user_id }}
action: input_text.set_value

but it returns Error: Error rendering service target template: UndefinedError: 'dict object' has no attribute 'context'

I suggest to try again using the suggestion that I typed, instead of substituting some of the words for different words.

Again:

{{ this.context.user_id }}

1 Like

Look carefully at @karwosts post, which is the solution.

Perhaps the OP did not appreciate the distinction between this. and trigger. but it happens to be critical in this instance.

My apologies. I assumed the word “this” was a stand-in for trigger or event or some other word. Thank you for the help.