php 如何禁用Timber\Menu的回退功能?

jdgnovmf  于 2023-05-27  发布在  PHP
关注(0)|答案(1)|浏览(185)

在Timber中,我们可以使用Timber\Menu使标准WordPress菜单作为对象可用于Twig模板。这取代了wp_nav_menu()在开发WordPress主题时所做的事情。
WordPress将回退菜单到现有页面的列表,如果用户不分配。可以通过将fallback_cp参数传递给wp_nav_menu()来禁用此功能,如下所示:

wp_nav_menu(
    array(
        'theme_location' => 'primary',
        'fallback_cb'    => false, // Disables the fallback menu, which displays the pages added within your site.
    )
);

如何禁用Timber的这种回退功能?我在Timber的document中阅读并搜索了关键字fallback。没什么

46scxncf

46scxncf1#

我认为你应该使用条件来实现相同的功能,因为缺乏对fallback特性的支持。
您可以使用has_nav_menu()函数在模板中呈现菜单之前检查菜单是否分配给特定的主题位置。

if( has_nav_menu( 'primary' ) ) {
    $context['menu'] = new Timber\Menu("primary");
}

然后在Twig模板中,可以根据菜单是否存在于上下文中有条件地渲染菜单:

{% if menu %} 
   {% include "path/to/menu.twig" with {'menu': menu.get_items} %}
{% endif %}

这样,如果没有菜单被分配到“主”主题位置,则不会呈现菜单,从而有效地禁用了回退到页面列表。

相关问题