Add class to {{ link }} twig attribute

I’m trying to apply a button class to the {{ link }} attribute in code below.

<span{{attributes}}><a class="usa-button"{{ link }}</span> 

It displays correctly however the markup is not correct. I see an extra <a="" tag.

<a class="usa-button" <a="" href="http://sites.localhost/sites/default/files/Image%20styles%20for%20grid%20view_3.docx" type="application/vnd.openxmlformats-officedocument.wordprocessingml.document; length=14535">Image styles for grid view_3.docx</a> 

Any ideas on how to apply class cleanly?

How to rewrite the field of a Drupal 8 view with TWIG?

In drupal I created a view with the machine name cgv_product.

This view contains the fields “Product Name” and “Custom Text”.

In the “Custom Text” field, the {{ name }} token is available to display the product number.

I created a template with the name views-view-fields--cgv_produit.html.twig it works but if I put the token {{ name }} in the code, the token is not rendered.

How to display the product name token in my template ?


Using cache for twig variables in preprocess function

I implement a menu on a region using a preprocess function to get a link with an anchor for each block of it with a title. I made a preprocess function for region, in my theme, where I test the region machine name.

I first used the $ variables[‘elements’][XXX][‘#id’] to load each block, to find out if the label was set to be display. But I quickly discover that on my server, where the cache is on, the $ variables[‘elements’] only contain an array of cached render.

I then modify my preprocess hook to use the key of the $ variables[‘elements’], witch is finally the block key.

use Drupal\block\Entity\Block;  /**  * Implements hook_preprocess_region().  */ function MYTHEME_preprocess_region(&$  variables) {   if ($  variables['region'] == 'one_page') {     $  blocs_menu = array();     foreach ($  variables['elements'] as $  key => $  values) {       if (substr($  key, 0, 1) == '#') {         continue;       }       $  bloc_object = Block::load($  key);       if (is_object($  bloc_object)) {         $  bloc_settings = $  bloc_object->get('settings');         if ($  bloc_settings['label_display']) {           $  blocs_menu[] = array(               'id' => $  key,               'label' => $  bloc_settings['label'],           );         }       }     }     if (count($  blocs_menu)) {       $  variables['region_menu'] = $  blocs_menu;     }   } } 

And in my override file region–one-page.html.twig

{%- if region_menu -%} <nav class="page-nav-anchor">   <ul> {%- for menu in region_menu -%}   <li><a rel="scroll" href="#block-{{ menu['id'] }}">{{ menu['label'] }}</a></li> {%- endfor -%}   </ul> </nav> {%- endif -%} 

Everything is working well, but I would like to improve the concept :

  • Be able to detect if the cache is activated on the project
  • Include in cache my ‘region_menu’ variable, and generate it only when cache have to be rebuild.

If I understand well, the twig template is also cached, then it is maybe just not really necessary to declare the menu if cache is ON ?

The thing is I’m really lost in the D8 cache API. I think I have to deal with the cache tags, because I don’t have a render to cache.

I would appreciate some help, I cannot find some good (and easy) examples on the documentation or in the core modules.

Entity print get variable in twig template

I’m using entity print and I would like to get node variables in my twig template, so I can call them like {{ content.field_name }}.

I tried using a preprocess function but I’m not sure I’m doing things well.

Assuming I have a twig template called entity-print.html.twig, here the preprocess functions I tried :

function THEMENAME_template_preprocess_entity_print(&$  vars) {     $  vars['field_name'] = $  entity->get('field_name')->getValue();   } 

I also tried

  function THEMENAME_template_preprocess_entity_print(&$  vars) {     $  vars['field_name'] = $  entity->get('field_name')->value;   } 

I’m calling field_name with all of this twig variable for debugging purpose :

   1 {{ content.field_name.0 }}    2 {{ content.field_name.value }}    3 {{ content.field_name.0.value }}    4 {{ field_name.content }}    5 {{ content.field_name[0] }}    6 {{ node.field_name.value }} 

Nothing come. What am I doing wrong ? Do I have to make a custom module ?

How to add class to a file link in Twig

I’m trying to add a button class to an internal file URL. The field itself is a normal file field type. Below is the twig code that I have tried to use with no success. I’m also using this code in a twig field template.

{% for item in items %}  <a class="usa-button" href="{{ item.content['#url'] }}">{{ item.content['#title']}}</a> {% endfor %} 

How can I render HTML tags in a variable in a twig template?

I have a variable in my twig template called description.
The variable is a string with an html em tag in it. When I go to the webpage to view the field, the html em tags are stripped out of the string.
I am on a Drupal 8 site and my variable was rendered through
\Drupal::service('renderer')->render() The twig autoescape parameter is set to false.

Using the twig debugger, I can see that my markup object includes the html em tags so I know that the problem is how twig is processing the string.
I’ve read in other posts to use the |raw tag but this has no effect.
What can I do to make the HTML in my twig variable render properly?

Update: I’ve included a screenshot of my output from {{ dump(description) }} enter image description here

How to access raw data in twig template using views table format

I use a table format view to display a list of articles article-list using draggable views to allow editors to order the list. I customize the content of rows depending on a boolean field is_header and a formatted text field title_override. I have sub-themed views-view-table--article-list.html.twig to accomplish this. It works well enough.

In the template, I test the truth of is_header and the non-emptiness of title_override as follows:

    {% if row.columns.field_is_header|render|striptags|trim %} 


    {% if row.columns.field_title_override|render|striptags|trim %} 

These tests yield the proper results. Anything less than render|striptags|trim doesn’t work.


Is there a way to directly access the raw data values of these variables to avoid the render|striptags|trim overhead?

I’ve seen suggestions to use something like row._entity.field_is_header, but this way of using _entity seems to work only in templates for the HTML or Unformatted view styles. Seems like there should be an easy way to do this.

As a note, switching to using an HTML or Unformatted style doesn’t seem possible because AFAIK draggable views can be set up only with the table format.

How to add query parameters in twig using path()?

I am following the code snippet provided here

{# Link to frontpage view. #} <a href="{{ path('view.frontpage.page_1') }}">{{ 'View all content'|t }}</a>  {# Link to user entity/profile page. #} <a href="{{ path('entity.user.canonical', {'user':}) }}">{{ 'View user profile'|t }}</a>  {# Link to node page. #} <a href="{{ path('entity.node.canonical', {'node':}) }}">{{ 'View node page'|t }}</a>

As the function says path($ name, $ parameters, $ options), I want to add a link which has query parameters as shown in below


I tried implementing it as follows

<a href="{{                 path('',                {'node':},                 {'query': [                  'destination': path('view.blue_search.page_1'),                  'cookie[blue_referrer]':,                  'cookie[blue_type]':'node'                  ]                  }                )                 }}">Find a Distributor</a> 

but it gives an error

The website encountered an unexpected error. Please try again later.Twig_Error_Syntax: An array element must be followed by a comma. Unexpected token "punctuation" of value ":" ("punctuation" expected with value ","). in Twig_TokenStream->expect() (line 124 of /templates/node/node–product.html.twig). Twig_ExpressionParser->parseArrayExpression() (Line: 205)

Responsive background image in Twig template

I would like to render an image as background image in my Twig template. To optimize my resources I’d like to use a responsive image but I cannot find a way to use it for background images.

For a standard image I would use something like

img src="{{ file_url(node.field_with_image.entity.uri.value) }}" alt="my_alt" class="my_class"> 

How can I achieve that with a background image?

Autocalculate computed twig field

I’m building a form which should calculate some values during the form view. I’ve tried to use the computed twig field. The calculation is working after submission and also, when I move to the previous or next page but I want the field to be calculated immediately after the base values has been entered (jQuery/AJAX).

The calculation should look like

If theres no way of doing it automatically, how can I accomplish this using a “Calculate” button?

I hope somebody can help with this issue or give an example for a form which is using this kind of calculation.