get current url in twig template?

后端 未结 6 1362
粉色の甜心
粉色の甜心 2020-11-30 17:44

I looked around for the code to get the current path in a Twig template (and not the full URL), i.e. I don\'t want http://www.sitename.com/page, I only need

6条回答
  •  情话喂你
    2020-11-30 18:21

    In symfony 2.1 you can use this:

    {{ path(app.request.attributes.get('_route'), 
            app.request.attributes.get('_route_params')) }}
    

    In symfony 2.0, one solution is to write a twig extension for this

    public function getFunctions()
    {
        return array(
            'my_router_params' => new \Twig_Function_Method($this, 'routerParams'),
        );
    }
    
    /**
     * Emulating the symfony 2.1.x $request->attributes->get('_route_params') feature.
     * Code based on PagerfantaBundle's twig extension.
     */
    public function routerParams()
    {
        $router = $this->container->get('router');
        $request = $this->container->get('request');
    
        $routeName = $request->attributes->get('_route');
        $routeParams = $request->query->all();
        foreach ($router->getRouteCollection()->get($routeName)->compile()->getVariables() as $variable) {
            $routeParams[$variable] = $request->attributes->get($variable);
        }
    
        return $routeParams;
    }
    

    And use like this

    {{ path(app.request.attributes.get('_route'), my_router_params()|merge({'additional': 'value'}) }}
    

    You won't need all this unless you want to add additional parameters to your links, like in a pager, or you want to change one of the parameters.

提交回复
热议问题