2012-02-18 89 views
17

如何從樹枝模板獲取當前網址?樹枝模板引擎:獲取當前網址

我使用Twig和PHP,沒有任何其他框架。

+0

爲什麼不傳遞當前URL作爲模板變量?或者你可以編寫一個輸出URL的模板標籤。 – 2012-02-18 07:09:19

回答

6

查找當前URL

當前的URL由Web服務器提供,並寫入$_SERVER超級全局。運行這個小腳本<?php echo '<pre>'; print_r($_SERVER);,通過您的服務器和根目錄找到您正在查找的值。在這個問題上

相關問題:

The PHP manual describes the nature of the available $_SERVER values here

獲取URL在嫩枝

之後,你有網址,你需要在樹枝模板實例調用​​當把它作爲一個模板變量。例如,你可以編碼。

$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 }}語法。

+0

我想知道是否有任何內部工具(變量ot方法)從Twig獲取URL? – nKognito 2012-02-18 07:37:34

+0

你可能會發現一些已經寫好的代碼,但是檢索當前的URL不在模板引擎的範圍內,所以我非常懷疑Twig是否有內置的東西。我當然找不到任何東西。 – erisco 2012-02-18 07:48:10

0

這裏我發現它使它與sliex框架通用。 我想我的解決方案並不完美,但它完成了工作。

在PHP代碼

添加以下代碼:

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

然後在你的枝杈模板,你可以做

{{ app.current_url }} 

讓我知道什麼是這種方法的botom線。

25

在Silex的以下作品和Symfony2的肯定,因爲它們共享請求類(我沒有,雖然測試是):

{{ app.request.getRequestUri() }} 
+5

'{{app.request.requestUri}}' – eightyfive 2014-07-31 04:52:12

+0

更好,是的。 – neemzy 2014-08-01 08:43:27

+1

已棄用,不應使用它。 https://github.com/silexphp/Silex/issues/1257#issuecomment-141058724 – Tieme 2016-07-06 15:09:10

2

記住最佳實踐,此時您應該使用Symfony\Component\HttpFoundation\RequestStack

請參閱http://symfony.com/blog/new-in-symfony-2-4-the-request-stack

由於Symfony的2.4,最好的做法是從來沒有注入請求服務,而是改爲注入request_stack服務[...]

所以在Silex的應用程序也可能與實現:

app.request_stack.getCurrentRequest.getUri