php - 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>
如何使链接正常工作并将我带到指定的锚点?
解决方案
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;
};
推荐阅读
- javascript - A-Frame如何实现拍照功能
- apache-kafka - 在集群环境中针对不同的kafka连接节点查询时,Kafka连接器的任务状态是不同的
- ios - 未定义符号:_OBJC_CLASS_$_AppsFlyerLib
- jenkins - Jenkins 构建步骤中的“MultiJob 阶段”和“在其他项目上触发/调用构建”有什么区别?
- amazon-web-services - 在 AWS Cloudformation 中,是否可以为 AWS::Logs::LogGroup 的 LogGroupName 设置通配符?
- python - Tkinter python:关闭窗口后有没有办法保存checkbutton变量的状态?
- google-bigquery - 如何查询数据集中的所有表并添加标识符?
- javascript - 如何在渲染时验证特定的 formik 字段
- javascript - 如何“阅读更多 - 仅在文本溢出时阅读更少(否则隐藏阅读更多)”
- django - 带排序的 DRF 分页