【问题标题】:Issue when adding second custom menu to global context将第二个自定义菜单添加到全局上下文时出现问题
【发布时间】:2018-10-11 16:03:29
【问题描述】:
Issue when adding second custom menu to global context - Unsupported operand types in /app/wp-content/plugins/timber-library/vendor/twig/twig/lib/Twig/Environment.php(462)

我正在着手获取第二个注册菜单并将其添加到标题模板中。我正在使用带有 Twig 模板的 Timber 插件。

我正在将第二个菜单添加到全局上下文中:

$context['custom-menu'] = new Timber\Menu( 'Custom Menu' );

并在我的 index.php 文件中调用菜单。

$context = Timber::get_context();
$context['posts'] = new Timber\PostQuery();
$templates = array( 'index.twig' );
if ( is_home() ) {
    array_unshift( $templates, 'home.twig' );
}
Timber::render( $templates, $context );

header.twig 文件包含在扩展为 index.twig 的 base.twig 中。这包括所有标题部分。

{% include "partial/user-menu.twig" with {'custom-menu': custom-menu.get_items} %}
{% include "menu.twig" with {'menu': menu.get_items} %}
{% include "partial/sl_logo.twig" %}
{% include "partial/sl_search.twig" %}

menu.twig 渲染得很好,但是当我添加用户菜单时,它给了我顶部的错误。当我删除 with {'custom-menu': custom-menu.get_items} 时,它给了我错误:Object of class Timber\Menu could not be converted to int

user-menu.twig 文件如下所示:

    <ul>
    {% for item in custom-menu %}
        <li class="{{ item.classes | join(' ') }}">
            <a target="{{ item.target }}" href="{{ item.link }}">{{ item.title }}</a>
             {% include "user-menu.twig" with {'custom-menu': item.get_children} %}
        </li>
    {% endfor %}
    </ul>

Timber Github repo 上的文档建议您可以将菜单添加到全局上下文中,并在 get_context 时简单地添加它们。

https://github.com/timber/timber/blob/master/docs/guides/menus.md

谁能帮助诊断这个问题?

【问题讨论】:

  • 你修复了你的错误吗?我和你有同样的问题。谢谢。
  • 我在使用 Timber Menu 时遇到了问题,最后发现它不喜欢包含破折号的名称。我将custom-menu 更改为custom_menu 并开始工作。

标签: wordpress twig wordpress-theming timber


【解决方案1】:

也许我会先向您提供我在相同情况下使用的。

functions.php添加

function add_to_context( $data ){
    //menu
    $data['menu_primary'] = new TimberMenu( 'primary' );
    $data['menu_footer'] = new TimberMenu( 'footer' );
    return $data;
}

下次在需要的地方使用:

{% for item in menu_primary.get_items %}
...
{% endfor %}

【讨论】:

猜你喜欢
  • 2011-09-21
  • 2010-10-08
  • 1970-01-01
  • 1970-01-01
  • 2010-12-06
  • 1970-01-01
  • 2018-09-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多