2

I'd like to retrieve the src URL of an image.

{% image "@AcmeMyBundle/Resources/public/image/myimage.jpg" %}
    <img src={{ asset_url }}
{% endimage %}

How would I get the asset_url inside the controller?

e.g. http://example.com/images/c1ca79c_myimage.jpg

or even images/c1ca79c__myimage.jpg I tried:

$this->container
    ->get('templating.helper.assets')
    ->getUrl('@AcmeMyBundle/Resources/public/image/myimage.jpg');

But this returns the string /@AcmeMyBundle/Resources/public/image/myimage.jpg and not a URL.

4
  • do you need src URL, or absolute path within a file system? Commented Oct 30, 2014 at 19:16
  • SRC URL for external linking, not the filesystem. Commented Oct 30, 2014 at 19:37
  • Just curious as to what the use case is for needing that in the controller? Commented Oct 30, 2014 at 23:44
  • @Chausser Need to forward some information to a legacy page while it's being rewritten using symfony. A section of the legacy site is functioning in Symfony2. Due to the dynamic nature of the site some image urls change which the legacy site doesn't know about. The legacy page needs these urls to function properly which is why twig is being bypassed/not used at the moment. Commented Nov 3, 2014 at 15:50

4 Answers 4

4

Have you tried this:

$this->container
->get('templating.helper.assets')
->getUrl('bundles/acmemy/public/image/myimage.jpg');
Sign up to request clarification or add additional context in comments.

Comments

1

You could just use the twig asset helper:

$twig = clone $this->get('twig');
$twig->setLoader(new \Twig_Loader_String());
$rendered = $twig->render(
    '{{ app.request.getSchemeAndHttpHost ~ asset("bundles/acmemy/image/myimage.jpg") }}'
);
//Outputs - http://example.com/acmemybundle/images/myimage.jpg

OR you should even be able to do:

$twig = clone $this->get('twig');
$twig->setLoader(new \Twig_Loader_String());
$rendered = $twig->render(
    '{% image "@AcmeMyBundle/Resources/public/image/myimage.jpg" %}
     {{ asset_url }}
     {% endimage %}'
);

Comments

1

The other answers were close. What I really wanted was:

  $this
    ->get('templating.name_parser')
    ->parse('@AcmeBundle/Resources/dart/AcmeMain/web/main.dart')
    ->getPath()

Like I asked in my question I wanted to use the @ annotation.

1 Comment

This still produces the @ annotation. Can you advise how to get the URL!
1

It's not working in symfony 3 anymore

In symfony 3 use

$this->container->get('assets.packages')->getUrl($path);

Ex.

private function getAssets($path)
{
    return $this->container->get('assets.packages')->getUrl($path);
}

$this->getAssets(...your path...);

Comments

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.