2014-09-05 83 views
0

讓說我有一個控制器動作以下路線註釋:如何生成路線忽略額外傳遞的參數

* @Route("/post/{post_id}/", name="post.view") 
* @Route("/post/", name="post.current_view") 

而且我想用樹枝來生成這個網址:

{{ url(basePath~'view', {'post_id':post.postId}) }} 
//basePath will either be "post." or "post.current_" 

我目前得到的是:

domain.com/post/1/ 
domain.com/post/?post_id=1 

什麼,我想,雖然是要生成ignori第二路線納克傳遞給它,這樣我就只得到任何「額外」的參數:

domain.com/post/ 

有誰知道這是什麼,可以本地實現呢?我知道我可以正確使用路由器的自定義分支函數,然後我可以生成路由並去掉查詢字符串,但是我想避免這種情況,如果在某處我已經錯過了一個簡單的切換。

回答

1

解決方案#1只需要添加一個if從句

{% if BasePath == 'post.' %} 
    {{ url(BasePath~'view', {'post_id':post.postId}) }} 
{% elseif BasePath == 'post.current_' %} 
    {{ url(BasePath~'view') }} 
{% endif %} 

也許不是最優雅的,但應工作。

解決方案#2

劈裂網址帶有問號和獲得的第一個字符串

{% set myUrl = url(basePath~'view', {'post_id':post.postId}) %} 
{{ myUrl|split("?")|first }} 

解決方案#3或者您也可以通過擴展RoutingExtension類樹枝覆蓋URL功能。

Symfony\Bridge\Twig\Extension\RoutingExtension 

可以找到一個例子herepathurl應該是相同的。

你應該重寫這個功能

public function getUrl($name, $parameters = array(), $schemeRelative = false) 
    { 
     return $this->generator->generate($name, $parameters, $schemeRelative ? UrlGeneratorInterface::NETWORK_PATH : UrlGeneratorInterface::ABSOLUTE_URL); 
    } 

你的函數看起來是這樣的:

public function getUrl($name, $parameters = array(), $schemeRelative = false) 
{ 
    $yourUrl = parent::getUrl($name, $parameters = array(), $schemeRelative = false); 
    return strstr($yourUrl, '?' , true); 
} 

什麼ID OES它消除一切afther問號。

覆蓋您要添加到參數

twig.extension.routing.class: MyNamespace\MyRoutingExtension 
+0

不是一個球迷添加的默認類if語句所有的地方,但加入'|狹縫(「?」)| first'到底的鏈接不是太糟糕 – Chausser 2014-09-05 19:15:49

0

我想不會,你需要的preg_replace過濾器,這本身並不定義

相關問題