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"
Related
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.
I have a content type with a field field_gallery that has multiple images.
I would like to get all these images printed in my twig file: page--front.html.twig. So i want to get these images in my frontpage and not only in their nodes. So far i could get them in their nodes with
{{ file_url(node.field_image.entity.fileuri) }}
but not somewhere else (of course since its using node). Is this possible?
Should i create a preprocessor function for page? Any guidance for this?
Yes, This is possible. This question is have two sub tasks :
1) Creating page--front.html.twig file
For creation of this twig file, you'll have to clone file i.e. page.html.twig and rename it with page--front.html.twig
2) Fetch Raw values of Image fields
You need to update code in my .theme file:
function THEMENAME_preprocess_node(&$variables) {
if ($variables['node']->field_image->entity) {
$variables['image_url'] = $url = entity_load('image_style', 'medium')->buildUrl($variables['node']->field_image->entity->getFileUri());
}
}
Then in page--front.html.twig file I have this:
{% for item in image_url %}
<div class="featured-thumb">
<img src="{{ item }}"/>
</div>
{% endfor %}
I'm twig beginner, I Want to get the CSS file content and not the path to be clear, this file is located in:-
Bundle/Ressources/public/css/'~var~'/main.css
var is a dynamic variable, so I used the source function of twig, but it seems that I don't point to the right path. Here is my code:
<style>
{{ source('/Bundle/Resources/public/css/'~var~'/main.css', ignore_missing = true) }}
</style>
Any help please.
You are right. You are not using correct notation for the path.
In your case, if your bundle is named FooBundle, you should use:
{{ source('#FooBundle/Resources/public/css/'~var~'/main.css', ignore_missing = true) }}
If your file's location was inside Resources/views/ for example Resources/views/foo/bar.html.twig you could use even shorter variants:
{{ source('FooBundle:foo:bar.html.twig', ignore_missing = true) }}
or:
{{ source('#Foo/yourTemplate.html.twig', ignore_missing = true) }}
See also: http://symfony.com/doc/current/templating/namespaced_paths.html
I'm currently developing an applications that will need to use translations from my JavaScripts.
The bundle BazingaJsTranslationBundle seems to be good, but after I tried it I don't think it fits my needs. It generates all the translations for all my application's bundles. It can be heavy to load.
Do you know other bundles or tricks for that ?
Thank you for your help.
I had similar problem (large translation files) with BazingaJsTranslationBundle and I simplify this by:
#config.yml
bazinga_expose_translation:
default_domains: [ jsonly ]
locale_fallback: "%locale%"
create simple html twig to store your js variables and bazing expose them from this files
{# jsOnleVariables.html.twig #}
{% set var1 = 'Welcome'|trans({},'jsonly') %}
{% set var2 = 'Bye'|trans({},'jsonly') %}
dump variables
php app/console bazinga:expose-translation:dump web/js
and in your layout include only wanted variables
{# layout.html.twig #}
<script src="{{ asset('bundles/bazingaexposetranslation/js/translator.js') }}" type="text/javascript"></script>
{% if app.request.locale == 'pl' %}
<script src="{{ asset('js/i18n/jsonly/pl.js') }}" type="text/javascript"></script>
{% else %}
<script src="{{ asset('js/i18n/jsonly/en.js') }}" type="text/javascript"></script>
{% endif %}
Depending on your exact needs and circumstances, a simple object in json format can be a good enough dictionary. For example like this:
var dict = {
TextIdWelcome : "Welcome",
TextIdGoodBy : "Good by"
}
A usage example:
var elem = document.getElementById("WelcomeTag");
elem.innerHtml = dict["TextIdWelcome"];
You can generate such json object on your server side for the actual language selected on client side and you can retrieve it by your favourite method (jquery, XMLHttpRequest, etc), and just assign it to this dict variable.
If you need sentences with runtime dependent values in it, a simple basic trick might fit your needs. Let use some markup like %0, %1, etc in the translated text.
var dict = {
TextIdWelcome : "Welcome %0",
TextIdGoodBy : "Good by %0"
}
function tr(textId, runTimeValue1, runTimeValue2){
var text = dict[textId];
if(runTimeValue1 !== undefined)
text = text.replace("%0", runTimeValue1);
if(runTimeValue2 !== undefined)
text = text.replace("%1", runTimeValue2);
return text;
}
So a usage example:
var userName = "Jhon";
var elem = document.getElementById("WelcomeTag");
elem.innerHtml = tr("TextIdWelcome", userName);
Please note that this solution lacks several refined tricks (escaping markups, variable number of runtime values, efficient replace algorithm, etc), but in simple everyday cases this could be good enough. This trick is also very simple (so you can easily enhance it to your needs) and you can control 100% how exactly it should handle the dictionary. You can of course control when and what dictionary to load into the dict variable.
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