If you liked what you've learned so far, dive in!
Subscribe to get access to this tutorial plus
video, code and script downloads.
With a Subscription, click any sentence in the script to jump to that part of the video!
Login SubscribeWe sent the email, but it's missing its core content: info about the articles that each author wrote last week. That's no problem for us: we're already passing an articles
variable to the template via context()
. In the template, replace the <tr>
with {% for article in articles %}
:
... lines 1 - 2 | |
{% block content %} | |
... lines 4 - 12 | |
<row> | |
<columns> | |
<table> | |
<tr> | |
<th>#</th> | |
<th>Title</th> | |
<th>Comments</th> | |
</tr> | |
{% for article in articles %} | |
... lines 22 - 26 | |
{% endfor %} | |
</table> | |
</columns> | |
</row> | |
... lines 31 - 39 | |
{% endblock %} |
add the <tr>
, a <td>
and print some data: {{ loop.index }}
to number the list, 1, 2, 3, 4, etc, {{ article.title }}
and finally, how about: {{ article.comments|length }}
.
... lines 1 - 2 | |
{% block content %} | |
... lines 4 - 12 | |
<row> | |
<columns> | |
<table> | |
<tr> | |
<th>#</th> | |
<th>Title</th> | |
<th>Comments</th> | |
</tr> | |
{% for article in articles %} | |
<tr> | |
<td>{{ loop.index }}</td> | |
<td>{{ article.title }}</td> | |
<td>{{ article.comments|length }}</td> | |
</tr> | |
{% endfor %} | |
</table> | |
</columns> | |
</row> | |
... lines 31 - 39 | |
{% endblock %} |
That's good enough. Double check that by running the command:
php bin/console app:author-weekly-report:send
And... in Mailtrap... we are good.
Now let's turn to the glaring, horrible bug in our email! Ah! As I mentioned a few minutes ago, if you hover over the link its, gasp, broken! For some reason, it points to localhost
not our real domain... which is localhost:8000
. Close, but not right.
Hmm. In the template... yea... that looks right: {{ url('app_homepage') }}
. Ok, then why - when we click on the link - is it broken?
... lines 1 - 2 | |
{% block content %} | |
... lines 4 - 30 | |
<row> | |
<columns> | |
<center> | |
... line 34 | |
<button href="{{ url('app_homepage') }}">Check on the Space Bar</button> | |
... line 36 | |
</center> | |
</columns> | |
</row> | |
{% endblock %} |
We know that the url()
function tells Symfony to generate an absolute URL. And... it is. I'll run "Inspect Element" on the broken link button. Check out the href
: http://localhost
not localhost:8000
. The same thing would happen if you deployed this to production: it would always say localhost
. The URL is absolute... it's just wrong!
Why? Think about it: in the registration email - where this did work - how did Symfony know what our domain was when it generated the link? Did we configure that somewhere? Nope! When you submit the registration form, Symfony simply looks at what the current domain is - localhost:8000
- and uses that for all absolute URLs.
But when you're in a console command, there is no request! Symfony has no idea if the code behind this site is deployed to localhost:8000
, example.com
, or lolcats.com
. So, it just guesses localhost
... which is totally wrong... but probably better than guessing lolcats.com
?
If you're sending emails from the command line - or rendering templates for any reason that contain paths - you need to help Symfony: you need to tell it what domain to use.
To fix this, start by looking inside our .env
file. One of our keys here is called SITE_BASE_URL
.
... lines 1 - 32 | |
SITE_BASE_URL=https://localhost:8000 | |
... lines 36 - 39 |
It is the URL to our app. But, but, but! This is not a standard Symfony environment variable and Symfony is not currently using this. Nope, this is an environment variable that we invented in our file uploads tutorial for a totally different purpose. You can see it used in config/services.yaml
. It has nothing to do with how Symfony generates URLs.
Anyways, to fix the path problem, you need to set two special parameters. The first is router.request_context.scheme
, which you'll set to https
or http
. The other is router.request_context.host
which, for our local development, will be localhost:8000
.
Tip
In Symfony 5.1, instead of setting these 2 parameters, you can set 1 new piece of config:
# config/packages/routing.yaml
framework:
router:
# ...
default_uri: 'https://example.org/my/path/'
Now obviously, we don't want to hardcode these - at least not the second value: it will be different on production. Instead, we need to set these as new environment variables. And... hey! In .env
, the SITE_BASE_URL
is almost what we need... we just need it to be kind of split into two pieces. Hmm.
Check this out, create two new environment variables: SITE_BASE_SCHEME
set to https
and SITE_BASE_HOST
set to localhost:8000
.
... lines 1 - 31 | |
### END CUSTOM VARS | |
SITE_BASE_SCHEME=https | |
SITE_BASE_HOST=localhost:8000 | |
... lines 36 - 41 |
Back in services.yaml
, use these values: %env(SITE_BASE_SCHEME)%
and %env(SITE_BASE_HOST)%
... lines 1 - 5 | |
parameters: | |
... lines 7 - 9 | |
router.request_context.scheme: '%env(SITE_BASE_SCHEME)%' | |
router.request_context.host: '%env(SITE_BASE_HOST)%' | |
... lines 12 - 53 |
Cool!
The problem is that we now have some duplication. Fortunately, one of the properties of environment variables is that... um... they can contain environment variables! For SITE_BASE_URL
, set it to $SITE_BASE_SCHEME
- yep, that's legal - ://
and then $SITE_BASE_HOST
.
... lines 1 - 31 | |
### END CUSTOM VARS | |
SITE_BASE_SCHEME=https | |
SITE_BASE_HOST=localhost:8000 | |
SITE_BASE_URL=$SITE_BASE_SCHEME://$SITE_BASE_HOST | |
... lines 37 - 41 |
I love that trick. Anyways, now that we've set those two parameters, Symfony will use them to generate the URL instead of trying to guess it.
Tip
This works, but if you need to override the scheme or host in .env.local
, you would
also need to repeat the SITE_BASE_URL=
to set it again. A better solution would
be to set the SITE_BASE_URL
just once using a config trick in services.yaml
:
parameters:
env(SITE_BASE_URL): '%env(SITE_BASE_SCHEME)%://%env(SITE_BASE_HOST)%'
Try the command one last time:
php bin/console app:author-weekly-report:send
And... check it out in Mailtrap! Yes! This time the link points to localhost:8000
.
Next! Let's talk about attaching files to an email. Hmm, but to make it more interesting, let's first learn how to generate a styled PDF.
Hey Samuel,
Ah, yes, I see, it sounds like an edge case. Thanks for mention it! I think the problem is that there's no locale in the request that is handled I suppose by CRON in your case? So yes, request context helps with host and scheme as you set it explicitly via parameters, but it does not help with locale. Hm, but do you have a default locale set? If the locale wasn't specified explicitly, it should use default locale. I'd suppose it should work out of the box, but probably it's not.
Unfortunately I don't see a specific parameter name that would help with injecting locale, but I see that Symfony\Component\Routing\RequestContext service has setQueryString() method that should work for this, and I think you can create a listener that will inject a locale to that RequestContext. I suppose you can do it for ConsoleEvents::COMMAND event and probably for WorkerMessageReceivedEvent::class one to make it work with Cron.
At least, you can try to check it - add that listener for command, generate a URL and "dump(); die;" it.
I hope this helps!
Cheers!
Hi Victor,
First of all thank you for your help, very helpful indeed.
The scenario is a supervisor but in the essence is like a cron, you are right :)
Setting in the configuration file framework => default_locale parameter does not work in this case.
I played around with your idea about WorkerMessageReceivedEvent. It has a lot of sense, because any message to be handled will go through it.
Setting the _locale to the RequestContext instance works fine :) !!!
This helps not passing the _locale parameter to every twig url function call, which allows working with twig templates as a default web request. This small big detail helps working the team smoothly and without unexpected errors :)
In a short period of time we will be translating the website I am working on, so it will be a good moment for refactoring and for considering the same approach for the translator instance (in this case translator->setLocale), so translating a text like 'text-to-be-translated' | trans, will be shorter than writing every time 'text-to-be-translated' | trans([], 'DOMAIN', 'locale')
Again, thank you very much indeed for your help and I hope this helps to the community.
Regards! :)
Hey Samuel,
Thank you for your feedback and confirming that it did the trick for you! I'm really happy :)
Cheers!
In Symfony 5.1, the default_uri
option was introduced (https://symfony.com/doc/current/routing.html#generating-urls-in-commands). Is this a valid replacement for the scheme and host parameters used in this tutorial?
// composer.json
{
"require": {
"php": "^7.1.3",
"ext-iconv": "*",
"aws/aws-sdk-php": "^3.87", // 3.110.11
"composer/package-versions-deprecated": "^1.11", // 1.11.99
"knplabs/knp-markdown-bundle": "^1.7", // 1.7.1
"knplabs/knp-paginator-bundle": "^2.7", // v2.8.0
"knplabs/knp-snappy-bundle": "^1.6", // v1.6.0
"knplabs/knp-time-bundle": "^1.8", // v1.9.1
"league/flysystem-aws-s3-v3": "^1.0", // 1.0.23
"league/flysystem-cached-adapter": "^1.0", // 1.0.9
"league/html-to-markdown": "^4.8", // 4.8.2
"liip/imagine-bundle": "^2.1", // 2.1.0
"nexylan/slack-bundle": "^2.1,<2.2.0", // v2.1.0
"oneup/flysystem-bundle": "^3.0", // 3.1.0
"php-http/guzzle6-adapter": "^1.1", // v1.1.1
"sensio/framework-extra-bundle": "^5.1", // v5.4.1
"stof/doctrine-extensions-bundle": "^1.3", // v1.3.0
"symfony/asset": "^4.0", // v4.3.4
"symfony/console": "^4.0", // v4.3.4
"symfony/flex": "^1.9", // v1.17.6
"symfony/form": "^4.0", // v4.3.4
"symfony/framework-bundle": "^4.0", // v4.3.4
"symfony/mailer": "4.3.*", // v4.3.4
"symfony/messenger": "4.3.*", // v4.3.4
"symfony/orm-pack": "^1.0", // v1.0.6
"symfony/security-bundle": "^4.0", // v4.3.4
"symfony/sendgrid-mailer": "4.3.*", // v4.3.4
"symfony/serializer-pack": "^1.0", // v1.0.2
"symfony/twig-bundle": "^4.0", // v4.3.4
"symfony/twig-pack": "^1.0", // v1.0.0
"symfony/validator": "^4.0", // v4.3.4
"symfony/web-server-bundle": "^4.0", // v4.3.4
"symfony/webpack-encore-bundle": "^1.4", // v1.6.2
"symfony/yaml": "^4.0", // v4.3.4
"twig/cssinliner-extra": "^2.12", // v2.12.0
"twig/extensions": "^1.5", // v1.5.4
"twig/inky-extra": "^2.12" // v2.12.0
},
"require-dev": {
"doctrine/doctrine-fixtures-bundle": "^3.0", // 3.2.2
"easycorp/easy-log-handler": "^1.0.2", // v1.0.7
"fzaninotto/faker": "^1.7", // v1.8.0
"symfony/browser-kit": "4.3.*", // v4.3.5
"symfony/debug-bundle": "^3.3|^4.0", // v4.3.4
"symfony/dotenv": "^4.0", // v4.3.4
"symfony/maker-bundle": "^1.0", // v1.13.0
"symfony/monolog-bundle": "^3.0", // v3.4.0
"symfony/phpunit-bridge": "^3.3|^4.0", // v4.3.4
"symfony/profiler-pack": "^1.0", // v1.0.4
"symfony/var-dumper": "^3.3|^4.0" // v4.3.4
}
}
I'd like to share a rare issue when sending async e-mails using the url twig function.
I always get the error: Unable to generate a URL for the named route "THE_ROUTE_NAME" as such route does not exist.
The project I'm working on has all routes prefixed with /en-en, like this:
And I also have in the parameters file (where SITE_BASE_SCHEME and SITE_BASE_HOST are defined in a .env file):
For this error to not be thrown I have to explicitly pass to the twig url function the _locale parameter, for example: url('frontend_legal_terms', {'_locale': locale})
I wonder if there is a better way to use the url twig function without passing the _locale parameter explicitly.
Many thanks in advance!