Drupal 8 conditional syntax - drupal

I'm looking for the proper syntax with a Drupal 8 conditional display of a link. I've been reading the twig documentation, and it's a significant jump from the PHP templating days so it's slow going. I need to conditionally display a link within the footer of a view.
In the past, this would be straightforward, i.e:
<?php global $user;?>
<?php if (user_access('administer nodes')):?>
<div class="foo">Shorthand link for admins</div>
<?php endif;?>
Getting this to work in Twig has been difficult as I'm unfamiliar with the syntax. Do I need to declare global user in some capacity? From this link here, Symfony 2: How do I check if a user is not logged in inside a template?, it seems that all I'd need to do is:
{% if is_granted('ROLE_ADMIN') -%}
<div class="foo">Shorthand link for admins</div>
{% endif %}
But I get an error when trying to submit that. Is ROLE_ADMIN not defined? How do I get the Symphony? (correct?) roles as defined within the D8 installation? I'm not sure what I'm doing wrong. Any assistance is appreciated.

If you need to check a specific permission try
{% if user.hasPermission('administer nodes') %}
<div class="foo">Shorthand link for admins</div>
{% endif %}

If you try to check the current user is administer in TWIG file , you can use
{% if is_admin %}
<div class="foo">Shorthand link for admins</div>
{% endif %}

Related

app.user variable empty (or not available?) in twig custom error message

According to symfony docs, the variable app is available "everywhere" for twig templates. I want to use app.user in a custom error message, but this variable does not actually seem to be available within these templates while in prod mode; it IS available in dev mode.
Example code:
// project/templates/bundles/TwigBundle/Exception/error404.html.twig
{% extends 'base.html.twig' %}
{% block body %}
{{ parent() }}
<div>
<h1>Page not found</h1>
<p>
Hello {{ app.user.name }}, {% <---- DOES NOT WORK %}
The requested page couldn't be located. Checkout for any URL
misspelling.
</p>
</div>
{% endblock %}
This is just a simple example, but illustrates the point. I've also tried to use
{% if is_granted('IS_AUTHENTICATED_FULLY') %}
// do something fancy
{% endif %}
and this also does not work. It also does not matter whether I extend base.html.twig or pull in the parent(), in all cases it does not work. I get no error messages at all. I have cleared by cache.
Any ideas about how to get this information to my template in prod mode?
I found in the documentation that the problem I describe is by design. From the docs:
Security & 404 PagesĀ¶
Due to the order of how routing and security are
loaded, security information will not be available on your 404 pages.
This means that it will appear as if your user is logged out on the
404 page (it will work while testing, but not on production).
The answer is to create my own exception controller (or extend the default ExceptionController).

CollectionType custom prototype via form_theme

I want to customize the way an entry of a CollectionType in a form will be rendered, that is the way the prototype is generated, I need my own HTML. So I need to do it with the Twig form_theme, but it doesn't work.
I am currently using Symfony 4.1.2.
Here is what I have for now:
In the template that renders the whole form:
{% form_theme form.additionalEmails.vars.prototype 'form/additionalEmail.html.twig' %}
In the form/additionalEmail.html.twig file:
{% block form_row %}
<div style="margin: 10px 0">
{{ form_label(form) }}
{{ form_widget(form.children.value) }}
<div>Recevoir les mails de type : {{ form_row(form.children.isUsedForAdminCommChannel) }}{{ form_row(form.children.isUsedForInfosPratiquesCommChannel) }}{{ form_row(form.children.isUsedForAgendaCommChannel) }}</div>
</div>
{% endblock %}
If I do that I get this error:
Key "value" does not exist as the array is empty.
What is weird is that if I replace the above code by this (by commenting the old one and adding the new line):
{{ dump(form.children) }}
I see that form.children is an array with 4 items and one named "value" so it is clearly broken.
Your help would be much appreciated, as I'm just an amateur dev trying to make a website for a youth movement ^^
Best Regards,
[EDIT]
Here is the form that includes the CollectionType:
https://gist.github.com/MrPOC/a4af94cc5e577a1244dac59de5ea3506
The field is named "additionalEmails"
Just so I understand you correctly. You have a Form which contains a CollectionType and you want to change the prototype of that CollectionType?
If yes could you please post the Form with the CollectionType?
EDIT: Ok so here's how to overwrite the prototype template for a CollectionType.
First we have to find out what your forms unique_block_prefix is. You can find this by going to the page where this form is rendered, you then click in the symfony debug bar on the form icon. Then you have to expand the View variables block and look for unique_block_prefix.
I assume your block prefix could look like this _user_type the name of the block you would overwrite would then be _user_type_additionalEmails_entry_widget (for more details please read the link provided below)
You can replace the widget part with row or label depending on what you want to overwrite (I would suggest trying to overwrite them all to see what exactly changes because I don't know of the top of my head)
In twig you would then take your block prefix and overwrite the prototype field in the same way you would overwrite any other field
{% block '_user_type_additionalEmails_entry_widget' %}
//Content
{% endblock %}
What I wrote down here is what I found out after reading https://github.com/symfony/symfony-docs/issues/6056 (read HeahDude' comment specifically)
I hope this helps!

Symfony: check if sessions exists in Twig

Is there a way to check if a session exists in the twig file? I want to switch between register or logout in my nav bar based on the session of the user.
I've searched a bit around and I could only found solution that do it in the controller.
Instead of directly checking session variables, I think you want to use what Symfony already has built-in to handle this. Please see this documentation:
{% if is_granted('IS_AUTHENTICATED_FULLY') %}
// show logout link
{% else %}
// show register link
{% endif %}
If you are using a Symfony version earlier than 2.8 you need to check for the existence of app.user first:
{% if app.user and is_granted('IS_AUTHENTICATED_FULLY') %}

Sensiolabs Insight : Twig templates should not contain business logic

I am actually running Sensiolabs Insight analysis on my Symfony 2.8 project.
I have a major issue with some of my Twig templates:
Twig templates should not contain business logic
The associated message is always the same :
Template too complex, depth of 10 is reached but only 5 is allowed.
For example this happens with the following template :
{% extends "FBNGuideBundle::layout.html.twig" %}
{% block title %}
{{ 'fbn.guide.page_title.bookmarks'|trans }}
{% endblock %}
{% block body %}
<div id="bookmarks" data-bookmark-ids="{{bookmarkIds|json_encode()}}">
{% if (restaurants|length > 0) %}
<div class="restaurants">
<h3>MES RESTOS</h3>
{% for bookmark in restaurants %}
<div class="bookmark" id="{{'bookmark-' ~ bookmark.id}}">
{{ bookmark.restaurant.name }}
<br>
<br>
<button>SUPPRIMER DES FAVORIS</button>
<br>
<hr>
</div>
{% endfor %}
</div>
{% endif %}
</div>
{% endblock %}
I tried to include in a separated file the code contained inside <div id="bookmarks"></div> and the depth has been reduced, but it is not a solution. I suppose that the problem is the access to some properties through several objects using getters (i.e bookmark.restaurant.slug).
I have a free plan so I am not able to access the documentation related to this warning. Anyone knows how to solve the problem ?
Thanks.
When you have too much logic in the view, you can put it in a custom Twig Extension. An advantage is that you don't need to duplicate the html if you are reusing that part in another page and of course, the code is more clear :)
In your case, you can write a new Twig Extension that renders all the bookmarks.
If you didn't build somethng similar till now, you can read about it here http://symfony.com/doc/current/templating/twig_extension.html

twig raw filter and functions

Hi everyone and sorry for my english,
I have a service who generates some html code which is passed to a twig template. I had to use the raw filter to show the code, but in that code I call a twig function.
This is the code stored in a var which is passed to the template by the controller.
'<li class="active" >Help</li>'
The resulting html code is the same, so {{ path('help') }} is not called.
Is there any filter to show the html code and call the functions?
Thanks
In your code, you are using {{path('help')}} for the hyperlink. Instead of using the twig path function, include the original Url in the code that is sent from the service. In the service. use
'<li class="active" >Help</li>'
I answered this before here: Twig: prevent parsing of client-side templates
{% raw %} deprecated
{% verbatim %}
<ul>
{% for item in seq %}
<li>{{ item }}</li>
{% endfor %}
</ul>
{% endverbatim %}
You should render your variable using the {% include(template_from_string(your_var)) %} twig block.
See the answer of Render content from string/database and generate links with twig for more info.

Resources