Cargar vista en un modal con Ajax con twig

tengo un problema. No me carga en ajax el contenido dinámico. Lo que quiero cargar es un formulario para modificar datos.

La url del route (el 202032 será dinámico cuando cargue bien):

$  router->map( 'GET', '/admin/registros/modificar/202032/','empresaControllerAdmin#Modificar','Modificar Registro'); 

Si llamo desde el navegador a la URL me lo carga bien. Entra en el controlador y me muestra la vista correctamente, pero si la llamo desde jquery/ajax, NO.

El index donde proceso todo lo tengo en:


Y el js está en


Cuando hago la llamada a la función, el navegador se encuentra en

temporal/admin/inicio/ (por eso meto los ../../ para bajar a temporal/ y que desde ahí ejecute la petición GET para pasarla por el enrutador y después ejecute el controlador.)

       $  (document).ready(function(){       $  ("#submit02").mousedown(function(){         $  ('#ModalDinamico').modal({show:true});         cargarContenido();       });     });      function cargarContenido(){               var url = "../../admin/registros/modificar/202032/";             $  .ajax({                                        type: "GET",                                 url: url,                                     //data: $  ("#formutareas").serialize(),                 success: function(data)                             {                   $  ('#bodyModalDetalles').html(data);                               }            });     };  

Modal detalle:

<!-- Modal Detalle --> <div class="modal fade" id="ModalDinamico" tabindex="-1" role="dialog" aria-labelledby="ModalDinamicoTitle" aria-hidden="true">   <div class="modal-dialog modal-dialog-centered" role="document">     <div class="modal-content">       <div class="modal-header">         <h5 class="modal-title" id="exampleModalLongTitle">Detalle</h5>         <button type="button" class="close" data-dismiss="modal" aria-label="Close">           <span aria-hidden="true">&times;</span>         </button>       </div>       <div class="modal-body">         <div id="bodyModalDetalles">Cargando...</div>       </div>       <div class="modal-footer">         <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>         <button type="button" class="btn btn-primary">Guardar Cambios</button>         </div>      </div>   </div> </div> 

¿Como puedo hacer un FOR con variables dinamicas con twig?

Estoy trabajando con twig, migrando un desarrollo que tenía hecho anteriormente. Me he topado con la necesidad de hacer un bucle for que en php lo hacía algo así: <?php for($ x=$ this->inid;$ x<$ this->find;$ x++){//TODO } ?>. Como pueden ver estoy tomando las variables inid y find del objeto que tengo. Los datos ya los obtengo con twig pero no tengo idea de como realizar este bucle con twig y la documentación no me logra dar una solucion especifica, ya que en esta se itera siempre sobre un array, algo como: {% for user in users %} <li>{{ user.username|e }}</li> {% endfor %}, y no es mi caso.

He intentado esto, {% set inicio = tpl.inid %}{% set final = tpl.find %}{% for x in +%}{{ x }}{% endfor %} pero obtengo el error:

Type: Twig\Error\SyntaxError Message: Unexpected token “end of statement block” of value “”. File: C:\xampp\htdocs\contablenift2\templates\informes\BalanceDePrueba.phtml Line: 29

Other twig syntax in commerce related templates

In some twig templates of the commerce modules, I can see the use of an alternate syntax:

Ex. in commerce-cart-flyout-offcanvas-contents-items.html.twig :

<% _.each(cart.order_items, function(orderItem, key) { %> 


<%= orderItem.total_price.formatted %></td> 

I can’t see any doc on this and as I am curious, I would like to know from where it is coming and what is the difference.

Twig get field value from panel page

I am trying to get the value of a field that is displayed in a panel page. I might be going about this all wrong, because I’m still getting used to Drupal 8. I want to display book information, including the ISBN value, which I use to make a link to Amazon.

I first tried a node template: node–book_page.html.twig and was able to do it by inserting the value of {{ content.field_isbn10.0 }} into the URL I added to the twig. This worked great, but when I tried doing the same thing to the template that I set up to be used by the panel page, nothing happens.

I know I have the custom layout twig working as it should, but I’m guessing that there is more to requesting the value than {{ content.field_isbn10.0 }} now that it’s going through node_view in Panels.

I have tried adding it to the panel page as entity_field:node:field_isbn10 as well as field_block:node:book_page:field_isbn10. I just can’t seem to get how to access the ISBN field value like I did in the node template.

Here’s what shows using kint: enter image description here

Here’s the top of that knit: enter image description here

Testing Autmation Strategy for Twig template

I am using Drupal 8 CMS for a media platform, which essentially uses twig templating engine. We are using component based approach, building small re-usbale building blocks instead of building the complete page.

Now each component has its twig file and stylesheet for css rules.

My question is can these what testing strategy suits better for automating testing strategy for the twig templates?

  • Unit Testing
  • Funtional Testing

Looks like phpunit has a way to test twig templates in isolation

But to me it appears to be overkill to have unit testing for templating engine, since twig templates are not meant to have complex business logic but yes it could be simple if else conditional branching on template.

Functional Test seems to be better candidate for this sort of assertions, but yes functional tests are slow since they are opinionated about database connections unlike unit tests.

Let me emphasis on my question again for a media platform using Drupal 8 as CMS what testing strategy suits better to test frontend twig templates? Is it

  • Unit Tests
  • Functional Tests

I wasn’t sure where this question fits better, I will close one based on response and suggestions.

Bucles FOR anidados en TWIG

Estoy bloqueado en la creación de un carrusel dinámico. Mi objetivo es imprimir 5 imágenes por slide. Así pues, con un primer bucle defino la cantidad de slide, y con un bucle anidado imprimo las 5 imágenes de cada slide. Mi propuesta de código funciona para la primera iteración, pero luego repite las imágenes impresas en el primer slide. He aquí mi código.

<section class="container sponsors"> <div class="row">     <div class="title-cont col-12">         <h2 class="text-center">Nos Partenaires</h2>         <hr class="border border-sponsors">     </div>     <div id="carouselSponsors" class="carousel slide" data-ride="carousel">          {% set maxItemsPerCarousel = 5 %}         {% set totalItems = sponsors|length %}         {% set initialCounter = 0 %}         {% set secondaryCounter = maxItemsPerCarousel %}          <ol class="carousel-indicators">             {% for i in range (1, (totalItems/maxItemsPerCarousel)) %}                 <li data-target="#carouselSponsors" data-slide-to="{{ i - 1 }}" class="{% if loop.first %}active{% endif %}"></li>             {% endfor %}         </ol>          <div class="carousel-inner">              {% for i in range (1, (totalItems/maxItemsPerCarousel)) %}                  <div class="carousel-item card-deck d-flex flex-row mt-5 justify-content-center {% if loop.first %}active{% endif %}">                      {% for key, sponsor in sponsors|slice(initialCounter, secondaryCounter) %}                         <div class="card col-4 col-sm-3 col-lg-2 p-lg-3 m-3">                             <a target="_blanket" href="{{ }}">                                 <img class="card-img-top" src="{{ sponsor.logoUrl }}" alt="{{ }}-id-{{ }}">                             </a>                         </div>                     {% endfor %}                      {% set initialCounter = initialCounter + maxItemsPerCarousel %}                     {% set secondaryCounter = secondaryCounter + maxItemsPerCarousel %}                  </div>              {% endfor %}          </div>         <a class="carousel-control-prev" href="#carouselSponsors" role="button" data-slide="prev">             <span class="carousel-control-prev-icon" aria-hidden="true"></span>             <span class="sr-only">Previous</span>         </a>         <a class="carousel-control-next" href="#carouselSponsors" role="button" data-slide="next">             <span class="carousel-control-next-icon" aria-hidden="true"></span>             <span class="sr-only">Next</span>         </a>     </div> </div> 

Drupal 8 Theming Twig

I have made a page view in table format list of some media articles having description and link as field Now I want to fetch the page view field in my page–front.html.twig. How to do. I want to show top 4 fields in front page. Thanks.

How to access session variables in Twig template?

In a custom module I specified in the hook_preprocess_page function the following session variable:

if (isset($  blockNameState) && $  blockNameState == 'open') {    $  tempstore->set($  blockNameState, 'close'); } else {    $  tempstore->set($  blockNameState, 'open'); } 

Let’s assume the above code ran with $ blockNameState = 'block1_state' and there is key/value pair ‘block1_state/open’ in the $ tempstore.

How do I access the key/value pair in a Twig template?

Can’t run the following PHP command in Twig:

$  blockNameState = $  tempstore->get($  blockNameState); 

Render block via twig template

I have programmatically created a block. In my module folder I added all suggested templates in a templates folder(mymodule/templates/suggestedtemplatename.html.twig).

However the block is not using any of them! I have enabled the theme debugger which gives me all the suggestions and describes which part of the page is produced from which template. I can see only block.html.twig producing html. I tried drush cr and uninstalling/installing the module

How to force twig output from my custom module instead from theme?

I’m new to Drupal, I create a module including block and twig. I want to call out my twig(modules/custom/footer_block/src/templates) and store data in there when execute build() in block.

However, it output a twig from theme folder(a templates folder inside the theme folder) that’s is not created by me.

How can I force to output from my module folder?

my block only the build() part (footerMenu_block.php)

public function build(){     return [         '#theme' => 'footer_menu',         '#address_title' => $  this->configuration['address_title'],         '#address_content' => $  this->configuration['address_content'],     ]; 


<div>        <h2>{{ address_title }}</h2>        <p>{{ address_content }}</p>  </div> 

my module(footer_block.module)

<?php function footer_block_theme($  existing, $  type, $  theme, $  path){   return array(     'footer_menu' =>       array(         'variables' => array(           'address_title' => '',           'address_content' => '',         ),       ),   ); } 

If I move my twig to that output folder (inside theme folder), it will be unable to store my data. If I make simple output ‘#markup’ in the build() that will work fine. Therefore, other codes in block should be working without problem.

My drupal version is 8.6.x. Hope can get help.