Help needed getting out of the habit of using TWIG as my Controller and Template files I'm currently using TWIG to manipulate variables that have been created in Drupal 8. For example, I have a template that contains the following logic:

{% if item.field_main_images[0] %}
  {% if item.field_main_images[0]['#item'].entity.uri.value != "" and item.field_main_images[0]['#item'].entity.uri.value is not empty %}
    {% set main_image_uri = item.field_main_images[0]['#item'].entity.uri.value %}
    {% set main_image_zoom = main_image_uri | image_style('item_zoom') %}
  {% endif %}
{% endif %}


and

{% set featured_content = '' %}
{% if item.field_item_specification.0['#text'] is not empty %}
  {% set featured_content = item.field_item_specification %}
{% endif %}


Am I missing something here because i'm getting caught in spending a lot of time figuring out the data structures of the objects and manipulating the logic within my TWIG templates. I've got a feeling that I should be doing this in either a preprocess function on the content type or by some other means.

How could I perform this same procedure using the drupal framework i.e. symphony to create/manipulate the variables before the use of a twig template.

Can anyone shed some light on this?

Thanks in advance.
You are right, this kind of code should be in your controller or in preprocess functions.
You should generate a  render array for each twig template, to be able to have a simple :

{{ image_with_zoom }}


In your twig file. Your controller could have something like :

  $renderArray = [];
  /* @var $item \Drupal\node\Entity\Node */
  if($item-&gt;field_main_images-&gt;count()){
    $image = File::load($item-&gt;field_main_images-&gt;target_id);
    $renderArray['image_with_zoom'] = [
      '#theme' =&gt; 'image_style',
      '#style_name' =&gt; '...',
      '#uri' =&gt; $image-&gt;getFileUri(),
      '#attributes' =&gt; [
        'data-zoom-url' =&gt;  ImageStyle::load('item_zoom')-&gt;buildUrl($image-&gt;getFileUri())
      ]
    ];
  }


Have also a look at field formatters, it allow you to get your own controls for each field you wish to display.
You can generate some skeleton with the drupal command :

$ drupal gpff


Have a look at documentation on this point, and the one in the drupal console. That's quiet important if you wish to reuse some display for a particular field as it looks like.