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) : {
        'title':item.title} }) %}
    {% endif %}

{% endfor %}

 # Use the pageData object to reference pages by id as needed
<p><a href="{{pageData.pageId5.url}}" class="button small alert">Request a Bid</a></p>

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.

  • Thanks for the reply. I don't think I can access an individual page by it's id from the navigation array though. (Or at least I don't know how to.) How would I grab the contact page's url for example from the navigation array directly? (can I do navigation.find('...wahtever')) The goal of the object is to prevent an additional call to craft.entries.section('pages').id('5').url, which would be another db query. – mjr Aug 21 '18 at 13:44
  • Well, you can just iterate through the array of results... but if you need to look them up by name or such, then sure, makes sense! – andrew.welch Aug 21 '18 at 14:11
  • Thanks, out or curiosity, if you wanted to grab the contact page's url, and you had already iterated over your nav with a for loop, what would you do? I wonder if I am being to obsessive, but I feel like the data for the contact page is "right there," just not in a way I can conveniently access. – mjr Aug 21 '18 at 19:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.