Answers.Body: <p>You're not specific about what optimisations or alterations you feel the code needs, but as a general optimisation advice: you should look into mitigating any so-called N+1 problems by implementing <a href="https://craftcms.com/docs/5.x/development/eager-loading.html" rel="nofollow noreferrer">eager-loading</a>.</p>
  <p>Essentially, the N+1 problem occurs whenever a query is executed inside a loop (for example, when looping over a collection of entries and querying for a &quot;list image&quot; on each entry, for every iteration of the loop) – where each iteration of the loop results in additional queries being executed, which might scale badly and result in poor performance as the number of elements involved increases.</p>
  <p>As far as I can tell there are a few N+1 problems in your code, for example here:</p>
  <pre><code>{% for block in entry.primaryImages .all() %}
      {% if block.type == 'image' %}
          {% set image = block.image.one() %}
          {% if image %}
              &lt;div class=&quot;hovershow&quot;&gt;&lt;img src=&quot;{{ image.getUrl }}&quot; alt=&quot;&quot;&gt;&lt;/div&gt;
          {% endif %}
       {% endif %}
  {% endfor %}
  
  </code></pre>
  <p>Note the <code>block.image.one()</code> query inside the loop; this represents an N+1 problem as each <code>block</code> will result in 1 additional query being executed (meaning that if you have 20 blocks, Craft will have to make at least 21 queries – 1 for the blocks themselves, and then 1 for each <code>image</code>). By implementing eager-loading, Craft can be told to essentially include the <code>image</code> field with the initial blocks query, bringing the amount of queries down to 1, regardless of how many blocks there are (or will be in the future).</p>
  <p>Eager-loading is traditionally done by passing an array of fields to eager-load to the <code>.with()</code> element query param. However, Craft 5 added a new &quot;lazy eager-loading&quot; feature via the new <a href="https://craftcms.com/docs/5.x/development/eager-loading.html#lazy-eager-loading" rel="nofollow noreferrer"><code>.eagerly()</code> query param</a>, which is generally a lot easier to use.</p>
  <p>Refactored to negate the N+1 query using the <code>.eagerly()</code> param, the above code would read like this (note the <code>.eagerly()</code> param being added to the <code>block.image.one()</code> query):</p>
  <pre><code>{% for block in entry.primaryImages .all() %}
      {% if block.type == 'image' %}
          {% set image = block.image.eagerly().one() %}
          {% if image %}
              &lt;div class=&quot;hovershow&quot;&gt;&lt;img src=&quot;{{ image.getUrl }}&quot; alt=&quot;&quot;&gt;&lt;/div&gt;
          {% endif %}
       {% endif %}
  {% endfor %}
  </code></pre>
  <p>Essentially, this would make Craft &quot;preload&quot; the <code>block.image</code> field, for all of the blocks in the <code>entry.primaryImages</code> field, without any additional queries.</p>
  <p>Not all things make sense to eager-load! A good rule of thumb is to only do this whenever queries happen within a <code>{% for %}</code> loop. It's also a good idea to enable <a href="https://craftcms.com/docs/5.x/reference/config/general.html#devmode" rel="nofollow noreferrer"><code>devMode</code></a> (only locally, though – never in production), as well as turning on the Debug Bar (via your admin accounts user preferences inside the Control Panel), which will make it easier to keep track of how many database queries each page load uses.</p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2024-09-30T16:53:34.240Z
Answers.Text: Hi Mats Mikkel,
  Thanks a lot for the help. Very well explained.
Answers.UserDisplayName: Kippi
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2024-09-29T22:31:18.997Z
Answers.LastActivityDate: 2024-09-29T22:31:18.997Z
Answers.UserDisplayName: Mats Mikkel Rummelhoff
Answers.Body: <p>The N+1 queries are one thing to look into.</p>
  <p>Another thing is readability and this can be improved by using a map:</p>
  <pre><code>    {% set colorBlocks = {
          'red': 'red-block.png',
          'yellow': 'yellow-block.png',
          'blue': 'blue-block.png',
          'lightblue': 'lightblue-block.png',
          'lightgreen': 'lightgreen-block.png',
          'pink': 'pink-block.png'
        } %}
  </code></pre>
  <p>In combination with:</p>
  <pre><code>&lt;div class=&quot;front-img-wrapper&quot;&gt;
            {% if colorBlocks[entry.colourBlocksInsteadOfImage.value] %}
              &lt;img src=&quot;{{ siteUrl }}site-images/{{ colorBlocks[entry.colourBlocksInsteadOfImage.value] }}&quot; alt=&quot;{{ entry.colourBlocksInsteadOfImage.value|capitalize }} Holder Image&quot;&gt;
            {% else %}
              &lt;img src=&quot;{{ image.getUrl }}&quot; alt=&quot;{{ image.title }}&quot;&gt;
            {% endif %}
          &lt;/div&gt;
  </code></pre>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2024-10-02T20:21:53.243Z
Answers.LastActivityDate: 2024-10-02T20:21:53.243Z
Answers.UserDisplayName: Niek
Body: <p>Ive successfully upgrade Craft 3 to Craft 5 but I need help to alter the code.
  I am a novice. Here is the code:</p>
  <pre><code>```  {# Individual Entry Start #}
        {% for entry in craft.entries.section(['work', 'text', 'research', 'video']) .orderBy('datePicker desc') .all() %}
        {% if entry.showEntryOnFrontPage %}
        &lt;div class=&quot;ind-news-wrapper&quot;&gt;
          &lt;a href=&quot;{{ entry.url }}&quot; data-ix=&quot;image-overlay-fade&quot; data-w-id=&quot;b6822a33-4635-2ea6-44b2-608a83d8fbf2&quot; class=&quot;hoverwrapper ind-work-wrapper-inner w-inline-block&quot;&gt;
             &lt;div class=&quot;date&quot;&gt;{{ entry.section }} {% if entry.tinyText %}/ {{ entry.tinyText }}{% endif %}{# {{ entry.datePicker|date('d.m.y') }} #}&lt;/div&gt;
             {% for block in entry.primaryImages.limit(1) .all %}
              {% if block.type == 'image' %}
              {% set image = block.image.one() %}
              {% if image %}           
            
        {% if entry.imageOnSectionPage.value == &quot;noImage&quot; %}
        {% elseif entry.imageOnSectionPage.value == &quot;showImage&quot; %}    
            
        {% if entry.colourBlocksInsteadOfImage.value == &quot;red&quot; %}
    &lt;div class=&quot;front-img-wrapper&quot;&gt;
    &lt;img src=&quot;{{ siteUrl }}site-images/red-block.png&quot; alt=&quot;Red Holder Image&quot;&gt;
    &lt;/div&gt;
    {% elseif entry.colourBlocksInsteadOfImage.value == &quot;&quot; %}
    &lt;div class=&quot;front-img-wrapper&quot;&gt;
    &lt;img src=&quot;{{ image.getUrl }}&quot; alt=&quot;{{ image.title }}&quot;&gt;
    &lt;/div&gt;
    {% elseif entry.colourBlocksInsteadOfImage.value == &quot;yellow&quot; %}
    &lt;div class=&quot;front-img-wrapper&quot;&gt;
    &lt;img src=&quot;{{ siteUrl }}site-images/yellow-block.png&quot; alt=&quot;Yellow Holder Image&quot;&gt;
    &lt;/div&gt;
    {% elseif entry.colourBlocksInsteadOfImage.value == &quot;blue&quot; %}
    &lt;div class=&quot;front-img-wrapper&quot;&gt;
    &lt;img src=&quot;{{ siteUrl }}site-images/blue-block.png&quot; alt=&quot;Blue Holder Image&quot;&gt;
    &lt;/div&gt;
    {% elseif entry.colourBlocksInsteadOfImage.value == &quot;lightblue&quot; %}
    &lt;div class=&quot;front-img-wrapper&quot;&gt;
    &lt;img src=&quot;{{ siteUrl }}site-images/lightblue-block.png&quot; alt=&quot;Blue Holder Image&quot;&gt;
    &lt;/div&gt;
    {% elseif entry.colourBlocksInsteadOfImage.value == &quot;lightgreen&quot; %}
    &lt;div class=&quot;front-img-wrapper&quot;&gt;
    &lt;img src=&quot;{{ siteUrl }}site-images/lightgreen-block.png&quot; alt=&quot;Blue Holder Image&quot;&gt;
    &lt;/div&gt;
    {% elseif entry.colourBlocksInsteadOfImage.value == &quot;pink&quot; %}
    &lt;div class=&quot;front-img-wrapper&quot;&gt;
    &lt;img src=&quot;{{ siteUrl }}site-images/pink-block.png&quot; alt=&quot;Blue Holder Image&quot;&gt;
    &lt;/div&gt;
    {% endif %}
    
    {% endif %}    
             
            {% endif %}
              {% endif %}
              {% endfor %}
            &lt;h2 class=&quot;front-work-heading&quot;&gt;{{ entry.title }}&lt;/h2&gt;
            
            {% if entry.summary %}&lt;div class=&quot;text&quot;&gt;{{ entry.summary }}&lt;/div&gt;{% else %}&lt;div class=&quot;text&quot;&gt;&amp;nbsp;&lt;/div&gt;{% endif %}
            
         &lt;!-- Rollover for background image function   --&gt;
         &lt;!--  
            {% for block in entry.primaryImages .all() %}
            {% if block.type == 'image' %}
            {% set image = block.image.one() %}
            {% if image %}
            &lt;div class=&quot;hovershow&quot;&gt;&lt;img src=&quot;{{ image.getUrl }}&quot; alt=&quot;&quot;&gt;&lt;/div&gt;
            {% endif %}
            {% endif %}
            {% endfor %}
          --&gt;
            
          &lt;/a&gt;
        &lt;/div&gt;
        {% endif %}
        {% endfor %}
        {# Individual Entry End #} ```
  </code></pre>
  
Tags: <templating><upgrades>
Title: Updated Craft. v3 to v.5 - need help to update code and optimise page load
ThreadText: # Updated Craft. v3 to v.5 - need help to update code and optimise page load
  
  (Asked by: username_0 on 2024-09-27)
  
  Ive successfully upgrade Craft 3 to Craft 5 but I need help to alter the code.
  I am a novice. Here is the code:
  
  ```
  ```  {# Individual Entry Start #}
        {% for entry in craft.entries.section(['work', 'text', 'research', 'video']) .orderBy('datePicker desc') .all() %}
        {% if entry.showEntryOnFrontPage %}
        <div class="ind-news-wrapper">
          <a href="{{ entry.url }}" data-ix="image-overlay-fade" data-w-id="b6822a33-4635-2ea6-44b2-608a83d8fbf2" class="hoverwrapper ind-work-wrapper-inner w-inline-block">
             <div class="date">{{ entry.section }} {% if entry.tinyText %}/ {{ entry.tinyText }}{% endif %}{# {{ entry.datePicker|date('d.m.y') }} #}</div>
             {% for block in entry.primaryImages.limit(1) .all %}
              {% if block.type == 'image' %}
              {% set image = block.image.one() %}
              {% if image %}           
            
        {% if entry.imageOnSectionPage.value == "noImage" %}
        {% elseif entry.imageOnSectionPage.value == "showImage" %}    
            
        {% if entry.colourBlocksInsteadOfImage.value == "red" %}
    <div class="front-img-wrapper">
    <img src="{{ siteUrl }}site-images/red-block.png" alt="Red Holder Image">
    </div>
    {% elseif entry.colourBlocksInsteadOfImage.value == "" %}
    <div class="front-img-wrapper">
    <img src="{{ image.getUrl }}" alt="{{ image.title }}">
    </div>
    {% elseif entry.colourBlocksInsteadOfImage.value == "yellow" %}
    <div class="front-img-wrapper">
    <img src="{{ siteUrl }}site-images/yellow-block.png" alt="Yellow Holder Image">
    </div>
    {% elseif entry.colourBlocksInsteadOfImage.value == "blue" %}
    <div class="front-img-wrapper">
    <img src="{{ siteUrl }}site-images/blue-block.png" alt="Blue Holder Image">
    </div>
    {% elseif entry.colourBlocksInsteadOfImage.value == "lightblue" %}
    <div class="front-img-wrapper">
    <img src="{{ siteUrl }}site-images/lightblue-block.png" alt="Blue Holder Image">
    </div>
    {% elseif entry.colourBlocksInsteadOfImage.value == "lightgreen" %}
    <div class="front-img-wrapper">
    <img src="{{ siteUrl }}site-images/lightgreen-block.png" alt="Blue Holder Image">
    </div>
    {% elseif entry.colourBlocksInsteadOfImage.value == "pink" %}
    <div class="front-img-wrapper">
    <img src="{{ siteUrl }}site-images/pink-block.png" alt="Blue Holder Image">
    </div>
    {% endif %}
    
    {% endif %}    
             
            {% endif %}
              {% endif %}
              {% endfor %}
            <h2 class="front-work-heading">{{ entry.title }}</h2>
            
            {% if entry.summary %}<div class="text">{{ entry.summary }}</div>{% else %}<div class="text">&nbsp;</div>{% endif %}
            
         <!-- Rollover for background image function   -->
         <!--  
            {% for block in entry.primaryImages .all() %}
            {% if block.type == 'image' %}
            {% set image = block.image.one() %}
            {% if image %}
            <div class="hovershow"><img src="{{ image.getUrl }}" alt=""></div>
            {% endif %}
            {% endif %}
            {% endfor %}
          -->
            
          </a>
        </div>
        {% endif %}
        {% endfor %}
        {# Individual Entry End #} ```
  
  ```
  
  **Tags:** templating, upgrades
  
  
  ---
  
  ## 2 answers
  
  ### Answer by username_1 on 2024-09-29. Score: 1
  
  You're not specific about what optimisations or alterations you feel the code needs, but as a general optimisation advice: you should look into mitigating any so-called N+1 problems by implementing [eager-loading](https://craftcms.com/docs/5.x/development/eager-loading.html).
  
  Essentially, the N+1 problem occurs whenever a query is executed inside a loop (for example, when looping over a collection of entries and querying for a "list image" on each entry, for every iteration of the loop) – where each iteration of the loop results in additional queries being executed, which might scale badly and result in poor performance as the number of elements involved increases.
  
  As far as I can tell there are a few N+1 problems in your code, for example here:
  
  ```
  {% for block in entry.primaryImages .all() %}
      {% if block.type == 'image' %}
          {% set image = block.image.one() %}
          {% if image %}
              <div class="hovershow"><img src="{{ image.getUrl }}" alt=""></div>
          {% endif %}
       {% endif %}
  {% endfor %}
  
  ```
  
  Note the `block.image.one()` query inside the loop; this represents an N+1 problem as each `block` will result in 1 additional query being executed (meaning that if you have 20 blocks, Craft will have to make at least 21 queries – 1 for the blocks themselves, and then 1 for each `image`). By implementing eager-loading, Craft can be told to essentially include the `image` field with the initial blocks query, bringing the amount of queries down to 1, regardless of how many blocks there are (or will be in the future).
  
  Eager-loading is traditionally done by passing an array of fields to eager-load to the `.with()` element query param. However, Craft 5 added a new "lazy eager-loading" feature via the new [`.eagerly()` query param](https://craftcms.com/docs/5.x/development/eager-loading.html#lazy-eager-loading), which is generally a lot easier to use.
  
  Refactored to negate the N+1 query using the `.eagerly()` param, the above code would read like this (note the `.eagerly()` param being added to the `block.image.one()` query):
  
  ```
  {% for block in entry.primaryImages .all() %}
      {% if block.type == 'image' %}
          {% set image = block.image.eagerly().one() %}
          {% if image %}
              <div class="hovershow"><img src="{{ image.getUrl }}" alt=""></div>
          {% endif %}
       {% endif %}
  {% endfor %}
  
  ```
  
  Essentially, this would make Craft "preload" the `block.image` field, for all of the blocks in the `entry.primaryImages` field, without any additional queries.
  
  Not all things make sense to eager-load! A good rule of thumb is to only do this whenever queries happen within a `{% for %}` loop. It's also a good idea to enable [`devMode`](https://craftcms.com/docs/5.x/reference/config/general.html#devmode) (only locally, though – never in production), as well as turning on the Debug Bar (via your admin accounts user preferences inside the Control Panel), which will make it easier to keep track of how many database queries each page load uses.
  
  > **Comments:**
  > **username_0**: Hi username_1 Mikkel, Thanks a lot for the help. Very well explained.  
  
  ---
  
  ### Answer by username_2 on 2024-10-02. Score: 0
  
  The N+1 queries are one thing to look into.
  
  Another thing is readability and this can be improved by using a map:
  
  ```
      {% set colorBlocks = {
          'red': 'red-block.png',
          'yellow': 'yellow-block.png',
          'blue': 'blue-block.png',
          'lightblue': 'lightblue-block.png',
          'lightgreen': 'lightgreen-block.png',
          'pink': 'pink-block.png'
        } %}
  
  ```
  
  In combination with:
  
  ```
  <div class="front-img-wrapper">
            {% if colorBlocks[entry.colourBlocksInsteadOfImage.value] %}
              <img src="{{ siteUrl }}site-images/{{ colorBlocks[entry.colourBlocksInsteadOfImage.value] }}" alt="{{ entry.colourBlocksInsteadOfImage.value|capitalize }} Holder Image">
            {% else %}
              <img src="{{ image.getUrl }}" alt="{{ image.title }}">
            {% endif %}
          </div>
  
  ```
  
  
  ---
  
  