2

I have a structure that looks like this:

  • Experiment ( Level 1)

    • Cages (Level 2)
    • Animals (Level 3)
    • Measurement (Level 4)

I am outputting this information into some inline JSON like so:

{% set mice = craft.entries({
    'section' : 'experiments',
    'level' : 3,
    'descendantOf' : entry.id,
}) %}

<script>
  var data = [
    {% for mouse in mice %}
    {
      "Cage": "{{ mouse.parent.title }}",
      "Mouse": "{{ mouse.title }}",
      "measurements": [
        {% for data in mouse.children.order('postDate') %}
        {
          "Date": "{{ data.postDate| date("d-M") }}",
          "Weight(g)": "{{ data.weight }}",
          "Length": "{{ data.length }}",
          "Depth": "{{ data.depth }}",
          "Tumor Volume": {{ data.tumourVolume }}
        }{% if not loop.last %}, {% endif %}
        {% endfor %}
      ]
    }{% if not loop.last %}, {% endif %}
    {% endfor %}
  ];
</script>

This is ok until entries start to increase, the TTFB begins to add up significantly - I am wondering if there is a way to eager load this sort of structure? The entries are very dynamic so caching isn't an option.

Thanks!

2
  • Have you every read this documentation craftcms.com/docs/templating/… or heard about the element api github.com/craftcms/element-api that returns ready to use transformed json? It does not really make sense to re-explain the docs just because you had not read them Feb 13 '18 at 13:34
  • Hi Robin — thanks for the reply, I have and I tried using the with: 'dependents' but it throws an array error. I looked around for the correct syntax but had no luck. I am using element API already but I thought it would be easier to just eager load the entries if it possible possible first instead of creating an end point. Feb 13 '18 at 13:43
3

To use eager-loading for the child elements add 'children' to the with parameter.

{% set mice = craft.entries({
    section: 'experiments',
    level: 3,
    descendantOf: entry.id,
    with: ['children', {order: 'postDate asc'}],
}) %}
0

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.