是否可以链接到Timber模板中的其他静态页面?

时间:2019-03-24 18:10:31

标签: php wordpress twig wordpress-theming timber

当前,要链接到“常见问题”页面,我具有以下内容:

Check out our <a href="{{ site.link }}/faq">FAQ</a> page.

但是,我希望能够链接到WordPress主题中的其他内部页面,而无需在其后手动编写URL参数。像这样:

Check out our <a href="{{ site.link('faq') }}">FAQ</a> page.

在Timber中不可能吗?我已经检查了文档,但没有看到任何引用,但是我觉得我一定缺少一些东西。

2 个答案:

答案 0 :(得分:2)

Wordpress具有两个功能来解决它​​:get_page_by_path()get_permalink()

get_page_by_path('page-slug');
get_permalink(page_id);

使用Timber,您可以编写类似calling a Timber function的内容:

{{ function('get_permalink', function('get_page_by_path', 'page-slug')) }}

但是可以肯定的是,您应该定义一个wp函数,使其不会发疯。您可以使用functions.php文件向WordPress添加功能,即使您应该已经为extends Timber定义了一个类(如果没有,请复制并粘贴它)

class StarterSite extends Timber\Site {
    public function __construct() {
        add_filter( 'timber/twig', array( $this, 'add_to_twig' ) );
        add_filter( 'timber/context', array( $this, 'add_to_context' ) );
        $this->add_routes();
        parent::__construct();
    }
    
    public function add_to_context( $context ) {
        $context['menu']  = new Timber\Menu();
        $context['site']  = $this;      
        return $context;
    }

    public function add_to_twig( $twig ) {
        $twig->addFunction( new Timber\Twig_Function( 'get_permalink_by_slug', function($slug) {
            return get_permalink( get_page_by_path($slug) );
        } ) );
        return $twig;
    }

}
new StarterSite();

如您所见,名为{_3_}的名为{_3}的get_page_by_slug接收到一个带有页塞的字符串。现在,您可以在模板上编写它:

{{ get_permalink_by_slug('page-slug') }}

享受:)

答案 1 :(得分:1)

您可以使用过滤器timber_context将页面添加到上下文中

add_filter('timber_context', 'add_to_context');

function add_to_context($context){
    /* this is where you can add your own data to Timber's context object */
    $extraLinks = [];
    $extraLinks['faq'] = get_permalink($faq_ID);
    $context['site']['extraLinks'] = $extraLinks;
    return $context;
}

因此您可以调用树枝文件

Check out our <a href="{{ site.extraLinks.faq }}">FAQ</a> page.

source