0
votes

I'm nearly new in Symfony2 and I have a little question:

I'm developing an email template, which has txt and html parts (no problem with it)

The only 'problem' I have is with the absolute paths of assets in TWIG.

Inside my email.html.twig file I have something like this:

<img src="{{ asset('images/my-image.png') }}" alt="My image" /> but it writes the route with relative path.

I discovered a little solution to add absolute paths, something like this:

{% set abs = app.request.scheme ~  '://' ~ app.request.host %}
<img src="{{ abs ~ asset('images/my-image.png') }}" alt="My image" />

It works! But I want to improve this solution and also learn to create custom filters (I read the documentation, but I got a bit lost)

I want to create something like this:

<img src="{{ asset('images/my-image.png' | absolute) }}" alt="My image" />

But I don't know how to properly override the assetics extension. Can you help me?

Thanks a lot!!

1

1 Answers

1
votes

Well, it is a little hard to copy paste the solution but I can make a short cookbook so you can go step by step and do it yourself:

1) You will have to implement Assetic/Filter/FilterInterface

2) If you look at the FilterInterface class, you will see that you have to to implement two methods: filterLoad and filterDump.

So, you will do something like this:

<?php

namespace You\YourBundle\Assetic\Filter;

use Assetic\Asset\AssetInterface;
use Assetic\Filter\FilterInterface;

class YourAsseticFilter implements FilterInterface
{ 
    public function filterLoad(AssetInterface $asset)
    {

          // do something

    }


    public function filterDump(AssetInterface $asset)
    {
        $content = $asset->getContent();

        // do something

        $asset->setContent($content);
    }


}

And after you to this, you have to something very similar to registering twig extensions in services.yml in YourBundle. Sure, it depens if you use YML, XML... configuration. I use yml so I will type it in yml :)

parameters:
    your_bundle.class: You\YourBundle\Assetic\Filter\YourAsseticFilter

services:
    your_bundle.assetic.your_assetic_filter:
        class: %your_bundle.class%
        tags:
            - { name: assetic.filter }
            - { alias: yourChosenNameForYourNewAsseticFilter }

And then you call it like | yourChosenNameForYourNewAsseticFilter, of course.