首页 > 解决方案 > Slim PHP 链接到另一个页面上的锚点

问题描述

我正在使用 Slim 框架开发一个网站。我正在尝试创建一个链接,将用户带到主页上的特定位置。

这是正常链接:

<a href="{{ path_for('home') }}">Home</a>

首先,我尝试编写一个绝对链接,例如:

<a href="https://example.com#anchor">Anchor</a>

但这不起作用并导致https://example.com/#anchor

这也不起作用:

<a href="{{ path_for('home#anchor') }}">Home</a>

如何使链接正常工作并将我带到指定的锚点?

标签: phptwigslim

解决方案


path_for树枝扩展无法处理锚点:

<a href="{{ path_for('home') }}#anchor">Home</a>

升级版:

class DecoratedTwigExtension
{
    private TwigExtension $twigExtension;

    public function __construct(TwigExtension $twigExtension)
    {
        $this->twigExtension = $twigExtension;
    }

    public function __call($name, $arguments)
    {
        if (is_callable([$this->twigExtension, $name])) {
            return $this->twigExtension->$name(...$arguments);
        }

        $message = sprintf('There is no callable method %s::%s', get_class($this->twigExtension), $name);
        throw new \BadMethodCallException($message);
    }

    public function pathFor($name, $data = [], $queryParams = [], $appName = 'default', $anchor = '')
    {
        $path = $this->twigExtension->pathFor($name, $data, $queryParams);
        // some manipulations with $path
        if ($anchor !== '') {
         
        }

        return $path;
    }
}

// Register Twig View helper
$container['view'] = function ($c) {
    $view = new \Slim\Views\Twig('path/to/templates', [
        'cache' => 'path/to/cache'
    ]);

    // Instantiate and add Slim specific extension
    $router = $c->get('router');
    $uri = \Slim\Http\Uri::createFromEnvironment(new \Slim\Http\Environment($_SERVER));
    
    // ======= the main lines =======
    $twigExtension = new \Slim\Views\TwigExtension($router, $uri);
    $view->addExtension(new \App\Namespace\DecoratedTwigExtension($twigExtension));

    return $view;
};

推荐阅读