【问题标题】:Slim PHP Link to an anchor on another pageSlim PHP 链接到另一个页面上的锚点
【发布时间】:2021-08-11 23:28:04
【问题描述】:

我正在使用 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>

我怎样才能使链接正常工作并将我带到指定的锚点?

【问题讨论】:

    标签: php twig slim


    【解决方案1】:

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

    &lt;a href="{{ path_for('home') }}#anchor"&gt;Home&lt;/a&gt;

    更新:

    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;
    };
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-29
    • 1970-01-01
    • 1970-01-01
    • 2017-03-05
    • 2020-09-24
    • 2018-12-25
    相关资源
    最近更新 更多