Twig模板引擎:获取当前网址

nKo*_*ito 17 php twig

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

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

nee*_*mzy 27

以下在Silex中工作,当然在Symfony2中它们共享Request类(我没有测试):

{{ app.request.getRequestUri() }}
Run Code Online (Sandbox Code Playgroud)

  • `{{app.request.requestUri}}` (6认同)

eri*_*sco 7

查找当前URL

当前URL由Web服务器提供并写入$_SERVER超全局.运行这个小脚本,<?php echo '<pre>'; print_r($_SERVER);通过您的服务器和root用户来查找您正在寻找的值.

有关此主题的相关问题:

PHP手册在此描述了可用$_SERVER值的性质.

在TWIG中获取URL

获得URL后,需要在调用render(...)Twig模板实例时将其作为模板变量传递.例如,您可以编写此代码.

$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));
Run Code Online (Sandbox Code Playgroud)

要在模板中使用该变量,请使用{{ variable_name }}语法.