简体   繁体   中英

Embedding a Webpack asset inside Twig's templated e-mail using Symfony Mailer

The Symfony's mailer documentation says one can embed an image easily:

<img
    src="{{ email.image('@images/logo.png') }}"
    alt="Logo">

However I have all my assets built by Webpack & Encore. I use the asset manifest file as well, because every asset has a chunkhash in its name.

How to embed an image using Twig in this case? I tried:

<img
    src="{{ email.image(asset('build/images/logo.png')) }}"
    alt="Logo">

But this doesn't work. I end up with an exception that "a template is missing". This works well of course if I use an image from a static location.

As documentation says: define a Twig namespace that points to whatever directory your images are stored in, for example:

# config/packages/twig.yaml
twig:
    paths:
        # point this wherever your images live
        public/build/: build

next, in your email template:

{# '@build/' refers to the Twig namespace defined earlier #}
<img src="{{ email.image('@build/logo.png') }}" alt="Logo">
<img src="{{ email.image('@build/subdir/logo.png') }}" alt="Logo">

this will not work if the constructed image has some random suffix, eg when .enableVersioning() is defined in webpack.config.js config file.


If you have enabled the versioning strategy, you can do the following:

# config/packages/twig.yaml
twig:
    paths:
        public/: public

and build the template name using the string concat operator ~ :

{# '@public' refers to the Twig namespace defined earlier #}
<img src="{{ email.image('@public' ~ asset('build/logo.png')) }}" alt="Logo">

There are two ways to get an image in your mail. First is an embedded image and second is just a link to an image somewhere on the net. If you want to embed an image you will have to attach the image to your mail:

$attachment = Swift_Image::newInstance($data, $filename, $mimeType)
    ->setDisposition('inline');

$cid = $message->embed($attachment); // Generates "cid:something"

Important is to show your image like this:

<img src="cid:something" ... />

So you have to render your template like this:

$twig->render('email/email.html.twig', [
    'cid' => $cid,
    ...
]);

and in your twig template:

<img src="{{ cid }}" ... />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM