Adding Google Tag Manager Datalayer elements for Drupal 9 webform

1. First copy and paste the confirmation twig template for webforms in the webforms module.

Then add a div to the twig template like this.

<div id="learning-objective-data">  </div>

In the div place your webform submission data token for the field you would like to grab

{{ webform_submission.data.Your Webform Field }} 

So it looks like this:

<div id="learning-objective-data">
{{ webform_submission.data.question1 }} 
 </div>

 

Now you can put all the submission fields you would like in the div and hide it with css.

 

:) Fields not hidden

Div hidden

 

Google Tag Manager DOM Element (User-Defined Variables)

What the data looks like in the preview

 

All my Template code for reference:

{#
/**
 * @file
 * Default theme implementation to webform confirmation.
 *
 * Available variables:
 * - progress: Progress bar.
 * - message: Confirmation message.
 * - back_url: URL to the previous webform submission.
 *
 * @see template_preprocess_webform_confirmation()
 *
 * @ingroup themeable
 */
#}
{{ attach_library('webform/webform.confirmation') }}

{% if progress %}
  {{ progress }}
{% endif %}

<div{{ attributes.addClass('webform-confirmation') }}>

  {% if message %}
  
    <div class="webform-confirmation__message">{{ message }}
     </div>
     <div id="learning-objective-data1">

      <div id="learning-objective-questions">
1. {{ webform_token('[webform:element:pre_question]', webform) }}: <br>
Answer: {{ webform_submission.data.pre_question }} <br>
2. {{ webform_token('[webform:element:post_question]', webform) }}: <br>
Answer: {{ webform_submission.data.post_question }}<br>

 {{ webform_submission.data.sid }}

  </div>
  <div id="learning-objective-user">
  {{ drupal_token('current-user:mail') }}<br>
{{ drupal_token('current-user:uid') }}<br>
{{ drupal_token('current-user:name') }}<br>
</div>
  <div id="learning-objective-url">
{{ drupal_token('current-page:url:absolute') }} <br>
</div>
 </div> 
  {% endif %}

  {% if back %}
  <div class="webform-confirmation__back">
    <a href="{{ back_url }}" rel="prev"{{ back_attributes }}>{{ back_label }}</a>
  </div>
  {% endif %}

</div>
{{ element.form_build_id }}
{{ element.form_token }}
{{ element.form_id }}