在木材树枝文件中循环

Loop inside timber twig file

我有一个名为 products 的自定义 post 类型和一个名为 type 的自定义分类法。

我需要显示类型列表以及每个类型中的三个 post。像这样

鸡肉
{鸡说明} |三 post 来自鸡肉类型的产品
猪肉
{猪肉说明} |三个 post 来自猪肉类型的产品

大约 6 种产品类型也是如此。

所以我在我的 wordpress .php 文件中有这个

$terms = get_terms('tipo', array('orderby' => 'id'));
foreach ($terms as $term) {
    $args = array(
        'post_type'   => 'producto',
        'tax_query' => array(
            array(
                'taxonomy' => 'tipo',
                'field'    => 'slug',
                'terms'    => $term->slug,
            ),
        ),
    );

    $context['product_'.$term->slug] = Timber::get_posts($args);
}

$context['cats'] = Timber::get_terms('tipo', array('orderby' => 'id'));

哪个应该让我 product_pork 和 product_chicken 以及所有其他

.twig 文件中我有这个

{% for cat in cats %}
    {{cat.title}}
    {{cat.description}}
{% endfor %}

在那之前一切都很好,但是当我尝试这样做时

{% for cat in cats %}
    {{cat.title}}
    {{cat.description}}
    {% for product in cat.slug %}
         {{product.title}}
    {% endfor %}
{% endfor %}

我一无所获,但如果我尝试这个

{% for cat in cats %}
    {{cat.title}}
    {{cat.description}}
    {% for product in product_pork %}
         {{product.title}}
    {% endfor %}
{% endfor %}

当然可以,我的问题是,有没有办法让它起作用?还是您想到另一种完全不同的方式?我乐于接受建议

非常感谢

问题出在这一行...

{% for product in cat.slug %}

cat.slug 是一个字符串,因此无法遍历它。试试这个代码...

$terms = get_terms('tipo', array('orderby' => 'id'));
foreach ($terms as &$term) {
    $args = array(
        'post_type'   => 'producto',
        'tax_query' => array(
            array(
                'taxonomy' => 'tipo',
                'field'    => 'slug',
                'terms'    => $term->slug,
            ),
        ),
    );

    $term->products = Timber::get_posts($args);
}

$context['cats'] = $terms;

树枝...

{% for cat in cats %}
    {{cat.title}}
    {{cat.description}}
    {% for product in cat.products %}
         {{product.title}}
    {% endfor %}
{% endfor %}