allow new methods in sandbox policy in twig (drupal 8)

drupal-8, symfony, twig, twig-extension

Solution

Drupal's twig sandbox policy (defined in core/lib/Drupal/Core/Template/TwigSandboxPolicy.php) reads from the global $settings array so you can define your own in your settings.php i.e.

// Override default twig allowed method list.
$settings['twig_sandbox_allowed_methods'] = [
  // Defaults:
  'id',
  'label',
  'bundle',
  'get',
  '__toString',
  'toString',
  // Additions:
  'url',
];

Problem

I am getting this error when using the "field collection" module : ``` Twig_Sandbox_SecurityError: Calling "uri" method on a "Drupal\field_collection\Entity\FieldCollectionItem" object is not allowed in "themes/communitylife/templates/content/node.html.twig" at line 83. in Drupal\Core\Template\TwigSandboxPolicy->checkMethodAllowed() (line 99 of core/lib/Drupal/Core/Template/TwigSandboxPolicy.php). ``` the code that causes the problem is this one : ``` <div class=" title-col col-md-7"> <a href="{{file_url(node.field_pressemappe_bildmaterial[key].getFieldCollectionItem().field_presse_bild_file.entity.uri.value)}}" target="_blank"> <strong> {{node.field_pressemappe_bildmaterial[key].getFieldCollectionItem().field_presse_bild_description.value}} <span class="file-type"> ({{node.field_pressemappe_bildmaterial[key].getFieldCollectionItem().field_presse_bild_file.entity.uri.value | slice(-3) }} </span>, <span class="file-size"> {{node.field_pressemappe_bildmaterial[key].getFieldCollectionItem().field_presse_bild_file.entity.size }}) </span> </strong></a> </div> ``` what is the best way to fix this ? is it by adding (uri) to the allowed methods in the sandbox policy ? if yes then how I can do that ? I read in the twig documentation that I can do something like this : ``` $policy = new Twig_Sandbox_SecurityPolicy($tags, $filters, $methods, $properties, $functions); ``` but I didn't understand how or where to put this code. Thanks in advance

Original source

Related problems