Gilberto Albino
Gilberto Albino

Reputation: 2744

Symfony Twig path() not working when using render

I have a layout that includes some chuck of code form a controller called "Layout"

In the header section I have:

{% block accessinfo %} {% render "/layout/accessinfo" %} {% endblock %}

It works pretty fine, the view file content is:

{% extends '::layout.html.twig' %}
{% block body %}
    {% if( is_logged == 0 ) %}
        Welcome, access your <a id="accessAccount" title="Access your account">here</a>.
    {% else %}
        Hi, <b><em> {{ is_logged_user_name }}</em></b>, <a id="doLogout" href="javascript:void;">(Logout)</a>. 
       <i class="icon-user"></i> <a href="{{path('account/manage')}}">Your Account</a>    
    {% endif %}
{% endblock %}

As one can figure out, path('account/manage') points to the Route named 'account/manage', but it's not returning the fully qualified URL to my project.

It returns:

http://localhost.project/account/manage

where it should be:

http://localhost.project/web/app_dev.php/account/manage

NOTE: I have path() all around my template files and they work like a charm.

IMPORTANT: I found out that when I call REQUEST URI inside the action method:

$this->get('request')->server->get('REQUEST_URI')

PHP will return the URL called by the render, in this case is:

/layout/accessinfo

Upvotes: 0

Views: 3307

Answers (1)

SirDerpington
SirDerpington

Reputation: 11470

Perhaps I'm not fully understanding your issue but it seems like you missunderstood the use of the path() and render() functions.

First of all if you like to render a controller and you follow the documentation here you would do it like this...

{{ render(controller('AcmeArticleBundle:Article:recentArticles') }}
{# with some parameters #}
{{ render(controller('AcmeArticleBundle:Article:recentArticles', {
    'max': 3
})) }}

This assumes you're using Symfony >= 2.2. This follows the bundle:controller:action pattern, which is called Controller Naming Pattern

For a normal use of the path() function you would always use the name of the route and not a hardcoded URL (as it seems like you're passing in URLs and not route names?)

Let's say your route is called accountmanager, your routing.yml should look like this example

# app/config/routing.yml
accountmanager:
    path:      /account/manage
    defaults:  { _controller:YourBundleName:YourControllerName:ControllerAction }

And with that in your routing.yml in twig the use of path() is simply achieved by writing {{ path('accountmanager') }}

See the documentation on this topic. Using the name of the route and not a URL pattern ensures that you're getting to the right page which also includes your environment settings (like app_dev.php for your dev environment)

Upvotes: 1

Related Questions