amteich / kirby-twig

Twig templating support for Kirby CMS
MIT License
48 stars 12 forks source link

page.children returns NULL #6

Closed PaulMorel closed 5 years ago

PaulMorel commented 5 years ago

Started a new project and wanted to use Twig. I have a dead simple template and page.children returns NULL.

Using Kirby 3.1.4.

{% extends "@templates/base.twig" %}

{% block main %}

    <article>

        <h1>{{ page.title.html }}</h1>
        {{ dump( page.children ) }}

        {% for section in page.children %}
            <section>
                {{ section.title.html }}
            </section>
        {% endfor %}

    </article>

{% endblock %}

{{ dump( page.children ) }} returns NULL and nothing inside the for block is rendered.

Everything works fine in an equivalent PHP template:

<?php snippet('header'); ?>

<article>

    <h1><?= $page->title()->html() ?></h1>  
    <?php dump( $page->children() ) ?>

    <?php foreach ( $page->children() as $section ) : ?>

        <section>
            <?= $section->title()->html() ?>
        </section>

    <?php endforeach; ?>
</article>

<?php snippet('footer') ?>

This template successfully outputs all of the page's children's titles. dump() outputs a Pages object.

Any ideas what might be happening?

seehat commented 5 years ago

Hey PaulMorel,

I tested this and found out that it works when saving page.children to a variable in a controller and passing it to the template. Also placing your code in an if block something like this helps:

{% if(page.hasChildren) %}
{% endif %}

Sry for the inconvenience. It has definitely something to do with twig. I will dig deeper to find the reason for this.

I hope you can work with it in the meantime with these tips.

seehat commented 5 years ago

I found the reason for this:

Twig calls to specific methods, like for instance page.children sometimes return NULL. This can occur, if there is also a public variable which is only initialized after calling the corresponding method.

{{ page.children }} returns NULL, because the public variable is returned. Please call the method instead like this: {{ page.children() }}.