【问题标题】:Blank 404 error page while using Twig template and Timber (WordPress)使用 Twig 模板和 Timber (WordPress) 时出现空白 404 错误页面
【发布时间】:2018-08-29 17:59:16
【问题描述】:

我正在为 WordPress 项目使用 Timber。我正在尝试让我的自定义 404 错误页面树枝模板显示在 404 错误上。目前,我的 404 错误显示为空白屏幕。但是,当我去路线时:/404 我的模板显示。我假设我的路由方式有问题,或者我在404.php 中遗漏了一些关键逻辑。

如何让我的 twig 模板显示我的 404 错误?

functions.php中的路由代码:

Routes::map('/404', function($params){
Routes::load('routes/404.php', null, $params, 404);
});

404.php:

<?php
$context = Timber::get_context();
$post = new TimberPost();
$context['page'] = $post;

global $wp;
$url = home_url($wp->request);
$context['url'] = preg_replace('#^https?://#', '', rtrim($url, '/'));

$context['global'] = get_fields('options');

Timber::render('views/pages/404.twig', $context);

404.twig:

{% extends "layouts/layout.twig" %}

{% block content %}
<div class="row row-is-centered">
<div class="col ns-col-is-8 lead-6 txt-center">
<h1 class="txt-size-5">Our apologies, we couldn't find {{url}}</h1>
</div>
</div>
{% endblock %}

【问题讨论】:

  • 检查您的 404.php 的放置位置。如果它不在主题的根文件夹中,它可能不起作用。另外,请查看@robertguss 的答案。他对路由问题有一些很好的指导。

标签: php wordpress twig timber


【解决方案1】:

您不应该为了让 WordPress 获取 404 页面而设置任何自定义路由。这是WP Codex on 404 Pages

此外,如果您使用的是 Timber starter 主题,则默认情况下它是开箱即用的。这是主题附带的文件,我只是在我目前正在处理的 Timber 项目上测试了这个,我还没有做任何事情来设置自定义 404 页面。我只有 Timber starter 主题默认附带的内容:

404.php

<?php
/**
 * The template for displaying 404 pages (Not Found)
 *
 * Methods for TimberHelper can be found in the /functions sub-directory
 *
 * @package  WordPress
 * @subpackage  Timber
 * @since    Timber 0.1
 */

$context = Timber::get_context();
Timber::render( '404.twig', $context );

404.twig

{% extends "base.twig" %}

{% block content %}
    Sorry, we couldn't find what you're looking for.
{% endblock %}

现在看起来路由也被弃用了:https://timber.github.io/docs/upgrade-guides/1.0/#routes

我不确定您在项目中的进度,但您可能想尝试升级到最新版本的 Timber 并使用他们的入门主题开始。他们提供了许多开箱即用的模板,使事情变得更容易。但是,如果您在项目中进行得很远,则应该小心升级,因为我确信会出现诸如路由功能之类的重大更改。上面引用的页面提供了一些关于您是否应该升级以及如何升级的有用信息。

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-23
    • 1970-01-01
    • 1970-01-01
    • 2020-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多