2016-03-09 50 views
1

我正在Symfony3中開發一個應用。部分應用程序由動態子域進行分區---子域由一個子彈表示。Symfony,Twig:持久路由參數

subdomains: 
    host: "{slug}.{domain}" 
    default: 
      slug: example 
    ... 

當在這樣的路線的本地例子上運行時,例如, http://a.localhost

當我創建的嫩枝的鏈接,或者使用{{ url('route') }}{{ path('route') }},子域始終是遺忘,並且在蛞蝓落在paramenter默認例如,總是使路線http://example.localhost

有沒有辦法隱含拷貝參數,或標記某些參數的執着,讓我沒有讓所有的鏈接包括這樣{{ url('route', {'slug' : slug}) }}蛞蝓,爲了留在域名?

謝謝

+0

是什麼探查說在「路由」面板上回答「路由參數」? (/app_dev.php/_profiler/latest?panel=router) –

+0

@TobiasXy slug參數在帶有* _locale *和* domain *參數的「路由參數」中按預期列出。沒有提供額外的信息。 –

回答

2

我已經生成的子域內鏈接的目的創建的TwigExtension

我寧願如果有可能使某些參數「持久」,如我在問題中提到的那樣。這些將隱含地通過相對路徑進行,但可能會用明確的參數選擇來消除。如果這是不可能的,我認爲這是比迄今手動添加參數和最佳選項更好的選擇。

擴展類

/** 
* ApplicationExtension constructor. 
* 
* @param Router $router 
* @param RequestStack $requestStack 
*/ 
public function __construct(Router $router, RequestStack $requestStack) 
{ 
    $this->router = $router; 
    $this->requestStack = $requestStack; 
} 

public function getFunctions() 
{ 
    return [ 
      new \Twig_SimpleFunction('domainPath', [ 
        $this, 
        'domainPath' 
      ]), 
    ]; 
} 

public function domainPath($route_name, $params = []) 
{ 
    if (!array_key_exists('slug', $params)) { 
     $params['slug'] = $this->requestStack->getCurrentRequest()->attributes->get('slug'); 
    } 
    return $this->router->generate($route_name, $params); 
} 

public function getName() 
{ 
    return 'application_extension'; 
} 

註冊服務(DI和Tag)

application.twig.application_extension: 
     class: ApplicationBundle\Twig\ApplicationExtension 
     arguments: ["@router", "@request_stack"] 
     public: false 
     tags: 
      - { name: twig.extension } 

使用模板

{{ domainPath('route_name') }}