【问题标题】:Timber hash link filter on menu links菜单链接上的木材哈希链接过滤器
【发布时间】:2017-06-25 08:00:51
【问题描述】:

我正在使用 Timber 在 WordPress 中构建单页主题,但我对它有点陌生,所以我对一些可能非常简单的东西有点迷茫。我只想使用过滤器将链接转换为哈希链接,但我什至无法让过滤器运行而不会出现错误(当我像下面这样添加它时,我只是得到一个损坏的站点)。这是我的functions.php 在我的主题中的样子(精确):

 class SIDSite extends TimberSite {

        function __construct() {
            add_theme_support( 'post-formats' );
            add_theme_support( 'post-thumbnails' );
            add_theme_support( 'menus' );
            add_filter( 'timber_context', array( $this, 'add_to_context' ) );
            add_filter( 'get_twig', array( $this, 'add_to_twig' ) );
            add_action( 'init', array( $this, 'register_post_types' ) );
            add_action( 'init', array( $this, 'register_taxonomies' ) );
            add_filter( 'hash_link', array( $this, 'hash_link' ) ); // Added this
            parent::__construct();
        }

        function hash_link ($string) { // function I added, is probably not 100% right but I can't even debug it
            if(substr($string, 0, 1) === '/') {
                $string = substr($string, 1);
            }

            return '#' . $string;
        }
}

这是我的menu.twig 文件:

{% if menu %}
    <ul>
    {% for item in menu %}
        <li class="{{item.classes | join(' ')}}">
            <a href="{{item.path | hash_link}}">{{item.title}}</a>
            {% include "menu.twig" with {'menu': item.get_children} %}
        </li>
    {% endfor %}
    </ul>
{% endif %}

我觉得我需要扩展其他内容,但将我的过滤器添加到整个网站应该在我的脑海中起作用。我可以做些什么来阻止这让我的网站崩溃?

【问题讨论】:

  • 您遇到的错误是什么?

标签: php wordpress filter twig timber


【解决方案1】:

你很接近,问题是 Twig 过滤器与 WP 过滤器完全分开,所以你需要在 Twig 上注册 yr 过滤器,而不是 WordPress。试试这个...

function add_to_twig( $twig ) {
    $twig->addFilter('hash_link', array( $this, 'hash_link' ));
    return $twig;
}

function hash_link( $string ) { /
    if(substr($string, 0, 1) === '/') {
        $string = substr($string, 1);
    }
    return '#' . $string;
}

【讨论】:

  • 感谢您的回答,它为我指明了正确的方向!只有两件事;我不得不将add_to_twig 过滤器重新添加到我的__construct 函数中,并且我不得不稍微改变我的函数;确保过滤器是Twig_SimpleFilter 并更彻底地检查 URL 以确保它可以更普遍地使用,但它现在可以工作了。
猜你喜欢
  • 2021-05-08
  • 1970-01-01
  • 1970-01-01
  • 2014-08-11
  • 2017-06-27
  • 1970-01-01
  • 2012-05-06
  • 2022-01-10
  • 2020-08-24
相关资源
最近更新 更多