b85411
b85411

Reputation: 9990

Using assets in controller (Symfony)

Currently I have this Twig code:

<img class="img-responsive" src="{{ asset('assets/images/features/feature-1.png') }}" alt="">

Can I pass that link through the controller instead?

ie. Say I have this variable:

$image = 'assets/images/features/feature-1.png';

What manipulation would I need to do to $image to have it "assetified" in such a way that I could then pass it to Twig and call it like:

<img class="img-responsive" src="{{ image }}" alt="">

?

Upvotes: 0

Views: 1920

Answers (1)

Johnny
Johnny

Reputation: 679

There really isn't anything magical about the Asset component. The "asset" twig extension simply calls the Asset component and may append a version string. If you wanted to do that in your controller you are free to use the Asset component directly. An example mostly from the docs

use Symfony\Component\Asset\Package;
use Symfony\Component\Asset\VersionStrategy\EmptyVersionStrategy;

$package = new Package(new EmptyVersionStrategy());

$imageUrl = $package->getUrl('/image.png');
// Now you can pass the $imageUrl to twig like any other variable.
// result: /image.png

Keep in mind that the asset twig extension works with the Asset component, not Assetic, which is a very different library.

See the documentation for the component itself. It's very simple.

Asset Component on Symfony.com

Upvotes: 2

Related Questions