Access pages data with fewer queries by creating an object in Twig I have the goal of querying the database once for page info, and then using it to display information on select pages site wide.

For example, I want to link the the contact page with using a url slug like "contact" (which might change)

My thinking is to query for pages, then loop over them in twig and create an object which I can access as needed.

Here is some example code, my question is - is the best Craft like way to do this? Am I missing something that should make this easier?

{#
 # Query for all the Pages
 #}
{% set navigation = craft.entries.section('pages').all() %}

{#
 # Create an object to quickly reference pages without making additional DB queries #}
 #}
{% set pageData = [] %}

{% for item in navigation %}
    {#
     # create a dynamic property if one doesn't already exist
     #}
    {% if not attribute(pageData, 'pageId' ~ item.id) is defined %}
        {% set pageData = pageData|merge({ ('pageId' ~ item.id) : {
        'id':item.id,
        'slug':item.slug,
        'url':item.url,
        'title':item.title} }) %}
    {% endif %}

{% endfor %}

{#
 # Use the pageData object to reference pages by id as needed
 #}
&lt;p&gt;&lt;a href="{{pageData.pageId5.url}}" class="button small alert"&gt;Request a Bid&lt;/a&gt;&lt;/p&gt;
So the only database queries in your example will be generated by:

{% set navigation = craft.entries.section('pages').all() %}


So creating an additional object doesn't serve the stated purpose of saving db queries. You can just access the navigation array directly.