Do I have to set a default value to a variable in Twig Normally in php I would have to set a default value to a variable but in Twig do I have to set a default value?

{% if content.my_field|render %}
  {% set offset = content.my_field['#items'].getString() %}
{% endif %}

&lt;div{{ attributes.addClass(classes).setAttribute('data-offset', offset) }}&gt;


I think it works but not sure if I should do this:

{% set offset = ''  %}
{% if content.my_field|render %}
  {% set offset = content.my_field['#items'].getString() %}
{% endif %}
It's controlled by a Twig environment setting, strict_variables:


  If set to false, Twig will silently ignore invalid variables (variables and or attributes/methods that do not exist) and replace them with a null value. When set to true, Twig throws an exception instead (default to false).


Drupal doesn't change the default value, so if you also leave that setting at false you won't need to make sure variables exist before referencing them. In fact, if you set it to true I imagine quite a few core and contrib would start throwing exceptions.