首页 文章

Timber / TWIG spearate特定类别的模板

提问于
浏览
0

所以在入门主题中我们有这个:

archive.php:

$templates = array( 'archive.twig', 'index.twig' );

$context = Timber::get_context();

$context['title'] = 'Archive';
if ( is_day() ) {
    $context['title'] = 'Archive: ' . get_the_date( 'D M Y' );
} else if ( is_month() ) {
    $context['title'] = 'Archive: ' . get_the_date( 'M Y' );
} else if ( is_year() ) {
    $context['title'] = 'Archive: ' . get_the_date( 'Y' );
} else if ( is_tag() ) {
    $context['title'] = single_tag_title( '', false );
} else if ( is_category() ) {
    $context['title'] = single_cat_title( '', false );
    array_unshift( $templates, 'archive-' . get_query_var( 'cat' ) . '.twig' );
} else if ( is_post_type_archive() ) {
    $context['title'] = post_type_archive_title( '', false );
    array_unshift( $templates, 'archive-' . get_post_type() . '.twig' );
}

$context['posts'] = new Timber\PostQuery();
Timber::render( $templates, $context );

根据我的理解,如果我导航到http://.......com/index.php/category/newcategory/,它应该 grab archive-newcategory.twig 文件作为模板 . 另一个例子,如果我去http://.......com/index.php/category/anothercat/它应该去抓 archive-anothercat.twig . 我有可能理解错误吗?因为如果是这种情况,我的启动主题不能按预期工作 . 我可以't find a dynamic solution in the docs, if this isn' t .

1 回答

  • 1

    它按预期工作 . 当 is_category() 为true时,存档将通过 get_query_var( 'cat' ) 获取类别ID,而不是类别名称 .

    您可以更新 archive.php 中的代码以添加您要使用的Twig模板 . 例如:

    else if ( is_category() ) {
        $term = new Timber\Term( get_queried_object_id() );
    
        $context['term']  = $term;
        $context['title'] = single_cat_title( '', false );
    
        array_unshift( $templates, 'archive-' . $term->slug . '.twig' );
    }
    

    或者您也可以使用不同的PHP模板 . 考虑list of PHP templates on wphierarchy.com . 在那里你可以看到你可以在主题根目录中使用 category.php 文件:

    $context = Timber::get_context();
    $context['title'] = single_cat_title( '', false );
    
    Timber::render( 'archive-category.twig', $context );
    

相关问题