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
Related
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 know that we can render the content of a controller in twig file like this:
{{ render(controller('FOSUserBundle:Security:login',{"baseTemplate": true})) }}
However, I don't know if we can pass the new template so that the controller will use it instead of the default. Anyone tried to override template in this way?
I don't really understand the issue here
If you do
{{ render(controller('FOSUserBundle:Security:login',{"baseTemplate": true})) }}
You could aswell do:
{{ render(controller('FOSUserBundle:Security:login',{"template": "your_template.html.twig"})) }}
Or
{{ render(controller('FOSUserBundle:Security:login',{"templateNumber": "4"})) }}
Where templateNumber is used in a condition inside your controller ?
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'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"
How can one get a twig global variable to maintain modification after changing it with includes? My desired output is "set # deeper" though I get "original setting".
app/config/config.yml
twig:
globals:
testvar: "original setting"
root.html.twig
{% include "MyBundle::levelone.html.twig" %}
{{ testvar }}
levelone.html.twig
{% set testvar = "set # levelone" %}
{% include "MyBundle::deeper.html.twig" %}
deeper.html.twig
{% set testvar = "set # deeper" %}
From a container aware object :
$this->get('twig')->addGlobal('ThomasDecauxIsAwsome', 4);
Interesting question and I don't know an answer but no amount fooling around with blocks and stuff will work. I looked in the generated php cache template files. When you echo a variable it looks like:
// {{ testvar }}
echo twig_escape_filter($this->env, $this->getContext($context, "testvar"), "html", null, true);
So basically it first looks for testvar in your local context. If not found then it looks in the global context.
When you set the value of test var you get:
// {% set testvar = 'level one' }}
$context["testvar"] = "level one";
So only the local context gets updated. The changed value goes away when the included template returns.
So by default at least it looks like global variables are really read only.
It might be possible to do this through an extension. I don't know enough about the internals.
Have you tried to define a global variable through Twig? You can do it in your config.yml file as follows:
twig:
globals:
my_global_var : myvalue
So {{my_global_var}} in your template will print myvalue
For more info read the official docs.
It's possible by defining a Twig Extension via Services, check here