0

I have this output from my twig template dump:

/var/www/html/vendor/twig/twig/lib/Twig/Extension/Debug.php:56:
array (size=7)
  'id' => string 'views_block:about-block_1' (length=25)
  'label' => string '' (length=0)
  'provider' => string 'views' (length=5)
  'label_display' => string '0' (length=1)
  'views_label' => string '' (length=0)
  'items_per_page' => string '3' (length=1)
  'background' => 
    array (size=1)
      0 => string '136' (length=3)

So my file id (fid) is 136. I'd like to know a way to get this file's url without having to use a preprocess function.

Can this be done? Would I have to do a custom twig function to achieve this? If so where would I add the code to extend twig?

ex:

$twig = new Twig_Environment($loader);
$function = new Twig_SimpleFunction('function_name', function () {
    // ...
});
$twig->addFunction($function);
0

So I decided to create a module to extend twig and get the file url from its fid.

get_url_from_fid git project

Source of src/GetUrlFromFid.php

<?php
namespace Drupal\get_url_from_fid;

class GetUrlFromFid extends \Twig_Extension{

  /**
   * {@inheritdoc}
   * This function must return the name of the extension. It must be unique.
   */
  public function getName(){
    return 'get_url_from_fid';
  }

  /**
   * In this function we can declare the extension function
   */
  public function getFunctions(){
    return array(
      new \Twig_SimpleFunction('get_url_from_fid',
        array($this, 'get_url_from_fid'),
        array('is_safe' => array('html'))
      )
    );
  }

  public function get_url_from_fid($fid){
    $file = \Drupal\file\Entity\File::load($fid);
    if(!is_null($file)){
      $uri = $file->getFileUri();
      return file_create_url($uri);
    }else{
      return false;
    }
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.