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

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') }}

Related

Symfony 4 how to set a global parameter for use in twig

I am after being able to set a parameter from my controller that can be accessed in twig to determine if the user is on an admin area or not to display an extra menu.
So perhaps I have an admin controller and inside the contractor I set a bool parameter to true as admin:
$this->isAdminArea = true;
Then in the template I need an if:
{% if isAdminArea %}
{% endif %}
And other controllers will either set $this->isAdminArea =false or somehow have it set default to false.
How can I achieve this?
You can define a global twig variable in config as stated in Symfony documentation:
# config/packages/twig.yaml
twig:
# ...
globals:
isAdminArea: false
And then override it in your controller whenever it needs to be true.
In your specific case it's also possible to just set the default value in place, using either the default or defined Twig filters
{% if isAdminArea|default(false) %}
{% endif %}
{% if isAdminArea is defined %}
{% endif %}
In the later case it doesn't matter to what value you'll set this into your admin controller, even false will do the job, which may be counter-intuitive.
Using a filter has the advantage of keeping all related bits into the same place, so unless you have the same check in multiple templates it should be considered more readable/maintainable solution.

get route controllers/action within rendered subcomponent in symfony3

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>

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

Symfony2: How to get request parameter

I have a route:
professor_identity_edit:
path: /professor/{id}/identity
defaults: { _controller: FrontBundle:ProfessorIdentity:edit }
How can I get the parameter {id} in twig.html file ?
I already tried app.request.query.get('id') but with no success.
Not a good thing but you can still do. Normally you would pass the info to Twig from the controller like #Maerlyn pointed out.
Get route parameters in Twig.
{{ app.request.attributes.get('_route_params') }}
AND
Gets whole bundle name in Twig.
{{ app.request.attributes.get("_controller") }}
Get route name in Twig.
{{ app.request.attributes.get('_route') }}
I found the solution:
{{ app.request.attributes.get('_route_params')['id'] }}

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)

Resources