how to access base url in twig from symfony 2 console? - php

I am porting my website which is in Kohana to Symfony 2 gradually. Right now I am writing backend command in Symfony2, e.g. cron to send email notifications.
How can I access base url in twig. Can I do some configuration so that accessing urls in twig from console and from http request to be same ?
I have already reffered to this,
http://symfony.com/doc/current/cookbook/console/sending_emails.html
http://symfony.com/doc/current/cookbook/templating/global_variables.html
here, it is given how to configure it, but it is not mentioned how to access it, I assume I have to use {{ router.request_context.host }}.
But my question is, isn't there any way to be consistent between console and HTTP ?
e.g. {{ url }} ?

Add following setting in parameters.yml,
router.request_context.scheme: http
router.request_context.host: domain.com
base_url: '%router.request_context.scheme%://%router.request_context.host%/'
and inside console command controller you can access like,
$host = $this->getContainer()->get('router')->getContext()->getHost();
$scheme = $this->getContainer()->get('router')->getContext()->getScheme();
$baseURL = $this->getContainer()->getParameter('base_url');

First, you must set the url (you're calling it base_url) in a route by adding the following lines to /app/config/routing.yml:
base_url:
pattern: /
After that, you must set the router.request_context parameters as mentioned in the Symfony cookbook.
Now that everything's setup, you can simply use the same url functions in Twig as you would do in your webpages:
{{ url('base_url') }}

This worked for me.
In config.yml:
twig:
globals:
base_url: "http://www.example.com/"
In twig template:
{{ base_url }}

Related

Shopware 6: How to Access Config Parameters in Twig Template of the Admin Module

I'm looking for a way to access configuration parameters in twig template of the admin module. I tried to access it by:
{{ shopware.config.pluginName.config.fieldName }}
The problem is that in the twig template of the admin module {{ shopware.config }} isn't available. I tried to access it by {{ dump(shopware.config) }} but it returns nothing.
Am I doing something wrong?
Is there alternative to access plugin's configuration parameters in the admin module?
Is there a way to pass php variables to twig template of the admin module?
Thanks in advance,
Cheers!
Try to use following service:
this.systemConfigApiService.getValues('domain', this.selectedSalesChannelId)
where domain is the Plugin name.
Of course, you should inject that service first
inject: ['systemConfigApiService']
Using that service you can provide config value to twig template.

Creating URLs containing the locale in Symfony 4

I am creating a Symfony 4 web app that supports multiple languages. The routing is done, so I can have /en/suchpage or /de/suchpage. I am now looking for a way to link to "suchpage" using the right locale.
Routing looks as follows:
suchpage:
path: /{_locale}/suchpage/
controller: App\Controller\SimplePageController::such
requirements:
maw: '%app.locales%'
defaults:
_locale: '%locale%'
I am using Twig, and it is from Twig templates that I need to be able to link to the right version of a page. This "works":
{{ path('suchpage', {'_locale': app.request.locale}) }}
It has two issues though:
I do not want to be repeating this all over the place. Something like {{ page('suchpage') }} would be much better. Does a function like this exist? Can path() be made to behave like this?
This fails if the locale was not specified in the request, as can happen, since it is not required on all pages (since some have a default).
There is a maintened bundle, JMSI18nRoutingBundle, to achieve what you need.
composer require jms/i18n-routing-bundle
Some usefull links about this bundle :
Packagist : https://packagist.org/packages/jms/i18n-routing-bundle
GitHub : https://github.com/schmittjoh/JMSI18nRoutingBundle

Symfony generate incorrect url with double /

I'm working on a symfony3 project, and i'm stuck with a problem,
We are sending emails that are twig based, with a button that has a link to our platform.
Button example
And the open document button link is the following one:
app.example.com/books/bookId/pageId
Which is generated through twig:
url("open_book", { bookId: book_id, pageId: page_id })
And the url is defined on a controller file, with annotations
#Route("/book/{bookId}/{pageId}", name="open_book")
So, the link that user gets on the email, is the original, but with double // before books, like this:
app.example.com//books/bookId/pageId
I'm working on last twig version, and I don't know if it can be symfony issue either, since its only happening on our prod environments (it works on local, yey)
If it helps, our routing.yml
app:
resource: "#BooksBundle/Controller/"
type: annotation
prefix: /
host: app.%host%
This is only happening with urls that are generated by twig. We are using jms translation and jms i18n bundles also, so I thought maybe its trying to set a null locale betwen / / like:
app.example.com/en/books/bookId/pageId
But instead of en, an empty language maybe.
Any idea to start with?
UPDATE 3/01/18
Hey! Thanks for all answers. It seems that was a problem with symfony configuration at the end...
On file parameters.yml:
router.request_context.scheme: '%env(ROUTER_REQUEST_CONTEXT_SCHEME)%'
router.request_context.host: '%env(ROUTER_REQUEST_CONTEXT_HOST)%'
router.request_context.base_url: '%env(ROUTER_REQUEST_CONTEXT_BASE_URL)%'
Then our value for base_url was /. Seems that was the real problem. Removing / on that param does the trick.
Thanks!!
For every route in the controller you are using prefix /:
app:
resource: "#BooksBundle/Controller/"
type: annotation
prefix: /
host: app.%host%
This means that every route like:
#Route("/book/{bookId}/{pageId}", name="open_book")
Will be prefixed with /. In the end this route path will be //book/{bookId}/{pageId}. Some libraries truncate path values, the other ones not.
So just remove prefix parameter completly or declare route's path without leading slash:
#Route("book/{bookId}/{pageId}", name="open_book")
try to replace this line
url("open_book", { bookId: book_id, pageId: page_id })
By
url("open_book", { bookId: book_id, pageId: page_id }) | replace({'//': "/"})
OR
{{ app.request.schemeAndHttpHost }} {{ path("open_book", { bookId: book_id, pageId: page_id }) }}

Symfony asset url when running from console

I want to add a asset (image) full url (with domain and base) in a twig template when running from a command line (Console Command). It's meant to be sent to email.
The problem is, using absolute_url(asset()) doesn't include the host and base path when running on console.
Also, as specificed in http://symfony.com/doc/current/console/request_context.html, it just works for urls, not for assets.
I've also tried to set the router context when running from console:
$context = $this->getContainer()->get('router')->getContext();
$context->setHost($defaultDomain);
$context->setScheme($scheme);
With no success. Any idea?
To configure the Request Context - which is used by the URL Generator - you can redefine the parameters it uses as default values to change the default host (localhost) and scheme (http)
# app/config/parameters.yml
parameters:
router.request_context.host: example.org
router.request_context.scheme: https
router.request_context.base_url: my/path
http://symfony.com/doc/current/console/request_context.html
#command
/** #var \Twig_Environment $twig */
$twig = $this->getContainer()->get('twig');
die($twig->render('view.html.twig'));
#view.html.twig
{{ absolute_url(asset('images/logo.png')) }}
#output
https://example.org/images/logo.png
In my application, special for this situation with emails, i added global variable into Twig configuration:
# app/config/config.yml
twig:
globals:
site_addr: "%site_addr%"
And setting this variable in parameters.yml
# app/config/parameters.yml
site_addr: https://some.site
And at last, in each email template i used this:
# AppBundle/Resources/views/Emails/layout.html.twig
<img src="{{ site_addr ~ asset('SomeAssetName') }}"/>
You have to define base_urls parameter.
framework:
assets:
base_urls: ['http://localhost:8000']
You can use this solution which doesn't require adding any variable or parameter on config and is the same function that is used by Twig for {{ absolute_url() }}
public function yourAction(AssetsHelper $assetsHelper, HttpFoundationExtension $httpExtension)
{
$assetsPath = $assetsHelper->getUrl('/img/test.jpg');
$assetFullUrl = $httpExtension->generateAbsoluteUrl($assetPath);
}
The complete url of your asset will be on $assetFullUrl

Generate URL to external route with UrlGenerator

With Silex (the PHP micro framework), it's possible to give names to existing controllers, so that we can easily generate urls to them later. Example:
$app->get('/gallery', function () {...})
->bind('gallery');
// Later on, in a template
{{ path('gallery') }}
I think this is really useful and I can't live without it.
But is it possible to register a route to an external website ? Say I'd like to generate urls to a google search, kind of
{{ path('google', {'search':'symfony'}) }}
// Would render to http://google.com/search?q=symfony
I take any idea :) Thx for your help !
path() is a Twig Extension for routing. Routing is to route an incoming URL to a controller action.
You can, however, create your own twig extension if you want a helper to easily create those standard outgoing URLs.
Take a look at: http://symfony.com/doc/current/cookbook/templating/twig_extension.html
You could then create an extension that turns {{ google('search string') }} into a URL. Only the imagination is your boundary.

Categories