Symfony 2 - Create link to uploaded assets - symfony

How can I link to uploaded assets dynamicaly with Symfony 2 and twig? I have a Controller that uploads files to the folder /web/uploads/entityName/fileName. In the template I'm trying to use the asset(document.path) function to create a link to the images. The problem is that the function returns the a path of /web/fileName. How can I add the missing path parameters (uploads/documents)?

Use the Twig string concatenation operator "~", like this:
asset('uploads/documents'~document.path)

You can send the url to Twig from the controller.
// Controller
$twig_params = array('uploadedURL' => $uploadedURL);
$this->render('VendorBundle:someTemplate.html.twig', $twig_params)
// Twig
<img src="{{ uploadedURL }}" />

Related

Symfony - display file stored outside public

Is there a possibility to display file in twig template when the the file is not stored inside public directory? Like call controller which would return binary response for requested file?
If you want to embed a controller response into a twig template you can use the render function.
{{ render(path('latest_articles', {max: 3})) }}
or
{{ render(controller('App\\Controller\\BlogController::recentArticles', {max: 3})) }}
Ref: https://symfony.com/doc/current/templates.html#embedding-controllers

Twig global variable into symfony controller

In my Symfony 4 application I use a Twig global variable to store the name of my website. I need to fetch its value both into my templates and controllers.
twig:
globals:
site_title: My blog
I am able to get it inside my Twig templates : {{ site_title }}
In my controller, I tried $this->getParameter('site_title') but :
The parameter "site_title" must be defined.
Try this:
$twigglobals = $this->get("twig")->getGlobals();
and you can get content by:
$site_title = $twigglobals["site_title"];

Generation logo image in email

I have a problem with link generation when I try to send emails.
In my .env file :
WEB_LOGO="http://test.loc/build/images/logo.png"
In my twig.yml
twig:
globals:
web_logo: '%env(WEB_LOGO)%'
My email template :
<img align="center" alt="" src="{{ web_logo }}" height="30">
The problem is that when I open folder /build/images the logo image is like this :
http://test.loc/build/images/logo.12345.png
But I generate like :
http://test.loc/build/images/logo.png
I can't use the generation like {{ absolute_url(asset('build/images/logo.png')) }} be cause I sendind email using an external service and I'm limited. Help please !
I don't know if there is a better way to do it but I would use the Finder component to get the filename like that:
$finder = new Finder();
$directory = 'http://test.loc/build/images';
$name = 'logo';
$finder->in($directory)->name("/{$name}/")->files();
$logoFile = iterator_to_array($finder, false)[0];
$logoPath = $logoFile->getRealPath();
Then you can pass the $logoPath variable as argument to your twig template.
Of course there will be a problem if you have multiple logo files like 'logo.1.png' and 'logo.29.png' etc.

In TWIG, is possible to get absolute url of a link with twig variables in it?

I have several URLs that look as follows:
{{domainID}}/action/{{userId}}/anotherAction
And the latter URL points to:
http://localhost/viewA/{{domainID}}/action/{{userId}}/anotherAction
However, If I try to load viewA from viewB through an iframe, the link inside viewA instead of pointing to:
http://localhost/viewA/{{domainID}}/action/{{userId}}/anotherAction
it will point to:
http://localhost/viewB/{{domainID}}/action/{{userId}}/anotherAction
and the user will end up in a 404 page if it follows the latter.
My question is:
Is there anyway to get the absolute path of a url built that way in twig?
EDIT
The route definition is:
#Route("/domain/details/{domainId}", name="domain_detailed_view")
I tried to get the absolute path this way:
{{ url({{domainID}}/action/{{userId}}/anotherAction) }}
but I get this error:
A hash key must be a quoted string, a number, a name, or an expression
enclosed in parentheses
The url or path functions take the route name, not the path. You can give it an associative array as an optional second argument if the route requires parameters.
For example:
{{ url('domain_detailed_view', { 'domainId': domainId, 'userId': userId }) }}
http://symfony.com/doc/master/reference/twig_reference.html
I know it's old and answered, but with symfony 3 & twig you can do:
{{ app.request.getSchemeAndHttpHost() }}
/* will match even port :) i.e.
* http://localhost:8000
* http://localhost
* http://example.com
*/
which is extremely helpful :D
You have two ways to do the same thing.
Generally you could use url() or path inside absolute_url function like so absoulute_url(path(...)). Consider the following:
// example 1:
{{ url('domain_detailed_view', { 'domainId': domainId, 'userId': userId }) }}
// example 2:
{{ absolute_url(path('domain_detailed_view', { 'domainId': domainId, 'userId': userId })) }}">
// note - those two do the same thing
Generally since Symfony 2.7 you could use absolute_url() with asserts and relative path also (relative to web/root folder). This is how you could use them to set absolute path to image in bundle and in main web folder:
[app/src/UserBundle/Resources/public/img/image.jpg]
<img src="{{ absolute_url(asset('bundle/user/img/image.jpg')) }}" /> // new way since 2.7 up
<img src="{{ asset('bundle/user/img/image.jpg', absolute: true ) }}" /> // old way below 2.7 removed in symfony 3.0
[web/css/img/some.jpg]
<img src="{{ absolute_url('css/img/some.jpg') }}" />
This is what symfony recommends to use while rendering email view.
http://symfony.com/doc/current/email.html

How to get current bundle in Symfony 2?

How can I detect in which bundle am I?
for exemple, when I'm in web.com/participants/list, I want to read "participants".
In order to get the bundle name in the controller:
// Display "AcmeHelloBundle"
echo $this->getRequest()->attributes->get('_template')->get('bundle');
And inside a Twig template:
{{ app.request.get('_template').get('bundle') }}
In order to get the controller name in the controller:
// Display "Default"
echo $this->getRequest()->attributes->get('_template')->get('controller');
And inside a Twig template:
{{ app.request.get('_template').get('controller') }}
In order to get the action name in the controller:
// Displays "index"
echo $this->getRequest()->attributes->get('_template')->get('name');
And inside a Twig template:
{{ app.request.get('_template').get('name') }}
AFAIK it's not yet possible (at least in a easy way). You should use reflection. I wrote a quick and dirty service to do get bundle name ang guess entity/repository/form names based on my conventions. Can be buggy, take a look at: http://pastebin.com/BzeXAduH
It works only when you pass a class that inherits from Controller (Symfony2). Usage:
entity_management_guesser:
class: Acme\HelloBundle\Service\EntityManagementGuesser
In your controller:
$guesser = $this->get('entity_management_guesser')->inizialize($this);
$bundleName = $guesser->getBundleName(); // Acme/HelloBundle
$bundleShort = $guesser->getBundleShortName(); // AcmeHelloBundle
Another possibility would be using kernel to get all bundles: Get a bundle name from an entity
Well you can get the controller of the current route by,
$request->attributes->get('_controller');
You can parse the bundle name from it.
You can get the bundle name in the controller simply like that:
// Display "SybioCoreBundle"
echo $this->getRequest()->attributes->get('_template')->get('bundle');
And inside a Twig template:
{{ app.request.get('_template').get('bundle') }}

Resources