【问题标题】:Twig templates engine: get current urlTwig 模板引擎:获取当前 url
【发布时间】:2012-03-09 12:13:15
【问题描述】:

如何从 Twig 模板中获取当前 URL?

我正在使用 Twig 和 PHP,没有任何其他框架。

【问题讨论】:

  • 为什么不将当前 URL 作为模板变量传入呢?或者你可以编写一个模板标签来输出 URL。

标签: php twig


【解决方案1】:

以下在 Silex 和 Symfony2 中有效,因为它们共享 Request 类(虽然我没有测试):

{{ app.request.getRequestUri() }}

【讨论】:

【解决方案2】:

查找当前网址

当前 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 }} 语法。

【讨论】:

  • 不知道有没有内部工具(变量ot方法)可以从Twig获取URL?
  • 你可能会发现一些已经为此目的编写的代码,但是检索当前 URL 不在模板引擎的范围内,所以我非常怀疑 Twig 有什么内置的。我当然找不到任何东西。
【解决方案3】:

http://api.symfony.com/2.3/Symfony/Component/HttpFoundation/Request.html

或:{{ app.request.getUri() }} 获取完整的 Uri。

【讨论】:

    【解决方案4】:

    牢记最佳实践,此时您应该使用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
    

    【讨论】:

      【解决方案5】:

      我发现这里有一些东西可以使它与 sliex 框架通用。 我想我的解决方案并不完美,但它可以完成工作。

      在您的 PHP 代码中添加以下代码:

      $app = new Silex\Application();
      // add the current url to the app object.
      $app['current_url'] = $_SERVER['REQUEST_URI'];
      

      然后在你的 Twig 模板中你可以做

      {{ app.current_url }}
      

      让我知道这个方法的底线是什么。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-05-08
        • 2012-12-21
        • 1970-01-01
        • 1970-01-01
        • 2012-10-28
        • 2023-03-29
        • 1970-01-01
        • 2019-09-04
        相关资源
        最近更新 更多