【发布时间】:2012-03-09 12:13:15
【问题描述】:
如何从 Twig 模板中获取当前 URL?
我正在使用 Twig 和 PHP,没有任何其他框架。
【问题讨论】:
-
为什么不将当前 URL 作为模板变量传入呢?或者你可以编写一个模板标签来输出 URL。
如何从 Twig 模板中获取当前 URL?
我正在使用 Twig 和 PHP,没有任何其他框架。
【问题讨论】:
以下在 Silex 和 Symfony2 中有效,因为它们共享 Request 类(虽然我没有测试):
{{ app.request.getRequestUri() }}
【讨论】:
{{ app.request.requestUri }}
查找当前网址
当前 URL 由您的 Web 服务器提供并写入$_SERVER 超级全局。运行这个小脚本<?php echo '<pre>'; print_r($_SERVER);,通过您的服务器和root 来查找您正在寻找的值。
关于这个主题的相关问题:
The PHP manual describes the nature of the available $_SERVER values here.
在 TWIG 中获取 URL
获得 URL 后,在 Twig 模板实例上调用 render(...) 时,需要将其作为模板变量传递。例如,您可以编写此代码。
$current_url = // figure out what the current url is
// pass the current URL as a variable to the template
echo $template->render(array('current_url' => $current_url));
要在模板中使用变量,请使用{{ variable_name }} 语法。
【讨论】:
去http://api.symfony.com/2.3/Symfony/Component/HttpFoundation/Request.html
或:{{ app.request.getUri() }} 获取完整的 Uri。
【讨论】:
牢记最佳实践,此时您应该使用Symfony\Component\HttpFoundation\RequestStack。
见http://symfony.com/blog/new-in-symfony-2-4-the-request-stack。
从 Symfony 2.4 开始,最佳实践是永远不要注入 request 服务,而是注入 request_stack 服务 [...]
因此,在 Silex 应用程序中,它可以通过以下方式实现:
app.request_stack.getCurrentRequest.getUri
【讨论】:
我发现这里有一些东西可以使它与 sliex 框架通用。 我想我的解决方案并不完美,但它可以完成工作。
在您的 PHP 代码中添加以下代码:
$app = new Silex\Application();
// add the current url to the app object.
$app['current_url'] = $_SERVER['REQUEST_URI'];
然后在你的 Twig 模板中你可以做
{{ app.current_url }}
让我知道这个方法的底线是什么。
【讨论】: