Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony Twig: Why use asset method?

Symfony recommends putting assets in the web folder.

They also comment about using the asset method. Why is the asset method needed? It takes up more characters than just putting in the link.

Why is this:

<img src="{{ asset('img/social/facebook.png') }}" />

better than this:

<img src="/img/social/facebook.png" />

I feel like I must be missing some reasons why.

like image 747
Eric Avatar asked May 24 '17 21:05

Eric


2 Answers

Your main directory is \web

in your config.yml (config/packages/framework.yaml using Symfony 5 and later):

assets:
    packages:
        downloads:
            base_path: images/yesterday/answers/download/
        attachment:
            base_path: stack/post/answers/ 

in this case downloads and attachment are your 'sections'

instead to write this code:

<img src="images/yesterday/answers/download/facebook.png" />
<img src="stack/post/answers/photo.jpeg" />

You can use:

<img src="{{ asset(facebook.png, 'downloads') }}" />
<img src="{{ asset(photo.jpeg, 'attachment') }}" />

because you don't have long path in the view and also you organize more your project classify for sections

more info here: http://symfony.com/doc/current/reference/configuration/framework.html#assets

like image 106
jjoselon Avatar answered Sep 24 '22 11:09

jjoselon


Because the Twig tag asset tag runs PHP code behind the scenes, it can alter the output. For example, I have a system running where the original files in the web/assets/js/ directory (and img/ or css/) are renamed based on the content - this means that when they are being served by a webserver, they can be marked as 'cache this file forever', and so hopefully a website reader will not have to download the same file again, because they have the first time the file was sent.

The asset tag in this instance is given the original filename, but that is just used as a lookup in an index to a uniquely renamed file - one that will never need to change, and so can be marked as cachable for potentially years.

like image 21
Alister Bulman Avatar answered Sep 23 '22 11:09

Alister Bulman