1

I'm trying to create my first twig estension

class UserExtension extends \Twig_Extension
{
public function getFunctions() {
    return array(
        new \Twig_SimpleFunction('userThumbImg', array($this, 'getUserThumbImg')),
    );
}

public function getUserThumbImg()
{
    $thumbImage = Repository::getInstance('users')->getUserImg(4, true);
    return $thumbImage['image'];
}

public function getName()
{
    return 'user_extension';
}
}

The static repository class simply reads the file with fread. I'd like to call the image from twig in this way

<img class="user-photo" src="{{ userThumbImg() }}" alt="" />

but I get a binary string. what can I do to display the image in my template? I haven't tried to return a response because this is not a controller, should I have to do in that way?

thanks

1 Answer 1

3

You always use a path to display an image. Save the image somewhere on the server and return that path. Or transform the image in a data: link and return that.

Sign up to request clarification or add additional context in comments.

4 Comments

the image is not under document_root, I need a way to display it from outside the document_root
Yeah but even if it not on the document_root, what he said still true
I don't understand, can you please provide an example? thanks
@user3174311 Just read this article about data:. The simplest way is to convert your image to base64: return 'data:image/'.$imageType.';base64,'.base64_encode($image); and then insert this string in your src attribute.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.