3

my question is simple. I use Symfony framework and Gaufrette filesystem (KnpGaufretteBundle) and I allready saved files (images) in filesystem.

Now I want show that images in twig. In controller I get the file:

$image = $filesystem->get($fie_key);

In variable $image is Gaufrette\File object. I would like to display that image in twig in <img> tag. But i don't know how to do that. Thank you for help

user1336101
  • 441
  • 1
  • 7
  • 17
  • Why do you need to read a file to put it in img tag? Just put the URL of the image!! – Broncha Feb 21 '15 at 15:55
  • Thank you for your quick answer. This approach makes sense. But how could I do it? Thanks – user1336101 Feb 21 '15 at 16:38
  • I'm sure you are saving your images to a public location. If not, generally you would configure your adapter to public folder, something like `web/uploads`. This way you can access your images using path "http:///uploads/". You dont even need to have any gaufrette operation. – Broncha Feb 22 '15 at 10:54
  • 1
    Yes, I store files in public area, so that I can access them as you write. But I was not sure that is best practice of doint it and I thought I need gaufrette. First, because it dangerous to provide direct link to files and second if I will you some cloud adapter, eg dropbox, I could not use this addressing. So I was convinced that I need use gaufrette "get" or "read" method to get images. Am I totaly out with these ideas? Thanks a lot for your patience. – user1336101 Feb 22 '15 at 22:05

1 Answers1

-1

Gaufrette is a file system abstraction library, seems like it doesn't implement any routing options for the files.

First option is creating a public route for your Gaufrette file system folder and reach the files as @Broncha mentioned.

The other option is; You can use Base64 encode to show images in the template, without passing a url for the image.

For e.q

<?php
require_once('vendor/autoload.php');

use Gaufrette\Filesystem;
use Gaufrette\File;
use Gaufrette\Adapter\Local as LocalAdapter;

$adapter = new LocalAdapter('files');
$filesystem = new Filesystem($adapter);

$loader = new Twig_Loader_Filesystem('templates');
$twig = new Twig_Environment($loader, array(
    'cache' => 'tmp',
));
//Probably the top part is redundant for you
//I've just set up a local twig and Gaufrette environment.

$file_key = "shareimage.png";
$file = $filesystem->get($file_key);
echo $twig->render('index.html', array('imageContent' => "data: ".$file->getMtime().";base64,".base64_encode($file->getContent())));

This is the simple template file;

<html>
    <body>
        <img src="{{imageContent}}" alt="Image" />
    </body>
</html>
Ugur
  • 1,679
  • 14
  • 20