get route controllers/action within rendered subcomponent in symfony3 - symfony

In my base.html.twig I render a component:
{% block header %}
{{ render(controller("AppBundle:Application\\Header:header")) }}
{% endblock %}
Is there a way to get the current route action/controller? i.e. the current url in the browser?
When I do var_dump($request->get('_route'));die; it results in null

If you want get the actual route, in your controller you can get the master request like this:
$this->container->get('request_stack')->getMasterRequest()->get('_route');

As I couldn't answer through a comment, I have to write this as an answer.
As mentionned above, this question might be a duplicate of:
Get current URL in Twig template
To get both the name of the current route and the current URL you can simply render them within your twig template by:
<p><strong>current route name</strong> :{{app.request.attributes.get('_route')}}</p>
<p><strong>current url: </strong> {{ app.request.schemeAndHttpHost ~ app.request.requestUri }}</p>

Related

Indicates if an URL is tight to current controller in Twig

assume you are in Twig template and want to indicate if you are on a controller with any action.
The simple process you can check a single route is
{% if app.request.attributes.get('_route') == 'app_user_list' %}
// code...
{% endif %}
But I need something with a wildcard to determine if the action is under current controller like 'app_user_*' to match also 'app_user_add' or 'app_user_delete'. It is nonsence to if-else all possible routes.
Any thoughts?
Thanks!
You can use the slice Twig filter, from the doc:
The slice filter works as the array_slice PHP function for arrays and
mb_substr for strings with a fallback to substr.
So you can archive as example of matching a group of routing with the prefix of app_user_ (app_user_add, app_user_delete, etc):
{% if app.request.attributes.get('_route')|slice(0,9) == 'app_user_' %}
// code...
{% endif %}
Hope this help

Show image name in Twig, relation one to one

I have a one to one relation between Player and Image. I have also this line in my controller:
var_dump($players[0]->getLinkedImage1()->getName());
It shows the name of an image correctly.
And I have also this line in the template:
{% for players in player %}
{{ player.age }}
{{ player.linkedImage1.name }}
{% endfor %}
but I get this error:
Impossible to access an attribute ("name") on a NULL variable ("")
I expected the last line shown the same name as in the controller.
EDIT: finally I found out that the property was public, that was the reason. Anway I still understand it..
My bad !
Look your for loop..
Try
{% for player in players %}
How did you write the property ? linkedImage1?
If you wrote something like linked_image_1 or linkedImage_1 you should call
{{ player.linked_image_1 }}
or
{{ player.linkedImage_1 }}
then twig will call the related getter according to : http://api.symfony.com/2.4/Symfony/Component/DependencyInjection/Container.html#method_camelize
If its a virtual getter you can directly access with :
{{ player.getLinkedImage1().name }}
or {{ player.getLinkedImage1().getName() }} `
You should try
{{ player.getLinkedImage1().getName() }}

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> Your Account
{% 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
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)

symfony2 - twig - how to render a twig template from inside a twig template

I have a xxx.html.twig file which shows a page, but when I want to refresh the page with different data and just update it with new data, I have a select and a submit button for it.
The thing is that I don't know how do I call an action in the controller which I pass parameters to from my twig and call for new data and then I render the same twig template again with new parameters.
How do I do so?
Here are a few different ways:
{{ render(app.request.baseUrl ~ '/helper/test', {"hostid2": hostid } ) }}
or
{% include 'MyCoreBundle:Helper:test.html.twig' with {"hostid2": hostid } only %}
or
{% render controller("MyCoreBundle:Helper:test", {'hostid2': hostid}) %}
Symfony 2.1:
{% render 'YourBundle:YourController:yourAction' with {'var': value} %}
Symfony 2.6+:
{{ render(controller('YourBundle:YourController:yourAction', {'var': value})) }}
And, of course, read the documentation.
I think some parts are depricated here.
To make the include work in latest Symfony 3.1.10, I solved it like this:
{% extends 'base.html.twig' %}
{% block body %}
{{ include('AppBundle:Default:inner_content.html.twig') }}
{% endblock %}
Note: include() with parentheses.
Then all the variables are included from the parent template. If you like to restrict some variables in the child template, you use with ... only (look over)

twig: find out if I'm in a subroute of a mainroute

I'm trying to exclude a menu if I'm in a subroute of a mainroute.
So for example this:
if route is /backend/* then exclude
else if route is /backend/admin/* don't exlude
else if route is /backend/admin/create then exclude
Is there a way to achieve this in twig with a few lines of code?
To get current path in twig you can use app.request.pathinfo.
Edit:
If you want to get route name of current url you can do it in following way.
Add Router object as template global variable.
#In app/config.yml
#.......
# Twig Configuration
twig:
globals:
router: #router
And then in your template,
{% set route_info = router.match(app.request.pathinfo) %}
{% set route_name = route_info._router %}
Then you can include/exclude your template based on route name.
Edit Again
Route name can be found in much simpler way.
{{ app.request.attributes.get('_route') }}

Resources