Generation logo image in email - symfony

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.

Related

Symfony2 : How to upload a file without Doctrine?

I use Symfony2.3. I have a form like this :
<form action="{{ path("member_update") }}" method="post" {{ form_enctype(form) }}>
{{ form_widget(form.pic) }}
...
{{ form_widget(form._token) }}
</form>
and i want to upload user pictures in a directory.Then i use this in controller :
$member , $form , $dm is defined...
if ($form->isValid()) {
// Handle profile picture upload process
$uploadDir=dirname($this->container->getParameter('kernel.root_dir')) . '/web/bundles/mybundle/myfiles';
$form['pic']->getData()->move($uploadDir,$member->getId());
// End of upload
$dm->persist($member);
$dm->flush();
return $this->redirect($this->generateUrl("member_profile"));
}
It must work,but i see this error:
Exception: Serialization of 'Symfony\Component\HttpFoundation\File\UploadedFile' is not allowed
1. in pathToMyProject...\vendor\symfony\symfony\src\Symfony\Component\HttpKernel\DataCollector\DataCollector.php line 27
2. at serialize(.....
What's the problem??!
The problem solved! I change this line in MemberType :
$builder->add('pic','file');
to this :
$builder->add('pic','file', array('mapped'=>false));
My mistake was that i must explain the "pic" field is not mapped to the Entity(or Document in Mongo,as my project). Else Symfony kernel try to put the value of "pic" in a field of Entity. And i have not any field that hold a file! I upload the picture in a directory and store only path to the picture within the entity. When i changed this,the problem solved easily! :-)
So keep in mind to explain all things clearly to Symfony!

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

Symfony2 Twig custom filter in asset

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!!
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.

Symfony 2 - Create link to uploaded assets

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 }}" />

Symfony 2: How to generate image paths in javascript file?

I've been googling this for long time! I need to show images on some menu hover and mouseout. The code is written in a js file. But the images path needs to be generated. Is there any way to generate image paths using something like this
{{ asset('bundles/mybundle/images/menu_down.png') }}
Can FOSJsRoutingBundle used to generate image paths in js files?
You could set global JS variables on your actual page:
<script>
var menuDownUrl = "{{ asset('bundles/mybundle/images/menu_down.png') }}";
</script>
And then set inside your javascript file to call the global variable: window.menuDownUrl
Then creates a dependency inside your javascript file, but allows you to set that image dynamically.
You can put an input hidden and set the path of the image.
<input type="hidden" id="img_path" value="{{ asset('images/circle_loading.gif') }}">
After that in jQuery you can use it like this
var img = "<img src=\'"+ $("#img_path").val() +"\'>";
$("div").html(img);
Agree with Nick answer, but he forgot the "quotes" around the {{ asset(...) }}.
So it should be written like this:
var menuDownUrl = "{{ asset('bundles/mybundle/images/menu_down.png') }}";
if you want window.menuDownUrl to work and not output you "undefined"

Resources