Division of Two Variables in Twig file. - symfony

I have the following two variables in twig file.
{%set sanstha_target%}
{%render 'FrontBundle:Datasheet:getCurrentTarget' with {'dealer':recent_entry.id,'month':recent_entry.year~recent_entry.month,'type':'3'}%}
{%endset%}
{%set sanstha_actual%}
{%render 'FrontBundle:Datasheet:getTotal' with {'datasheet':recent_entry.datasheet,'dealer':recent_entry.id,'type':'3'}%}
{%endset%}
The when I am going to divide this getting this error:
An exception has been thrown during the rendering of a template ("Notice: Object of class Twig_Markup could not be converted to int...
I need to get the percentage like this
{{ (sanstha_actual/sanstha_target)*100}}

I think you have to use two slashes, i.e.
{{ (sanstha_actual // sanstha_target) * 100 }}
as shown in the documentation:
//: Divides two numbers and returns the floored integer result. {{ 20
// 7 }} is 2

Related

Unexpected Jinja Template Behaviour in Custom Airflow Operator

I have made a custom sensor in Airflow which inherits BashSensor.
Sensor :
class MySensor(BashSensor):
def __init__(self, time, **kwargs): # {{ ts }} is passed as time in the DAG
self.time = time
cmd = f"java some-other-stuff {self.time}" # rendered/correct value for self.time
super().__init__(**kwargs, bash_command=cmd)
def poke(self, context):
status = super().poke() # returns True or False
if status:
print(self.time) # {{ ts }} is printed instead of rendered value
else:
print("trying again")
return status
When I look at the rendered tab for the operator task in DAG I see bash_command has the correct rendered value ({{ ts }} is passed as time).
The problem is whenever poke is called and True is returned, I see {{ ts }} in the print statement instead of the rendered value.
I expect self.time to have the rendered value (some timestamp) not {{ ts }} when I print it in poke function.
Both cmd and time are not templated field in your code so Jinja engine does not handle them. The reason you see the command being templated is because in the super call you do:
bash_command=cmd
and bash_command is templated field of BashSensor
So while the command is parsed to the correct string as expected the individual components that created it does not contain the render value.
To explain in some more details: time = "{{ ds }}" will always stay as this string. it will never be rendered.
When you do cmd = f"java some-other-stuff {self.time}" it becomes:
"java some-other-stuff {{ ds }}"
This string is assigned to bash_command which is templated field and when the code is executed the value of {{ ds }} is rendered.
To solve your issue you can simply add the parameters you want to template to the sequence:
class MySensor(BashSensor):
...
template_fields: Sequence[str] = tuple({'time'} | set(BashSensor.template_fields))
...

number_format usage in Drupal 8 Webform

I would like to format the numbers being displayed in a "Computed Twig" element in Drupal 8 Webform. I've tried Twig's "number_format" filter, but it does not work. I have this:
{{ (data.auswahl_oder_eingabe) * 202 / 1000000 * 25|number_format(2, ',', '.') }}
I would like to have only two decimals, the dot as a thousands separator and the comma as a decimal point. But I always get something like this:
53.025
So three decimals and the dot as a decimal separator. The format I would like to have in this case would be: 53,03 No matter what I write in that "number_format" definition, the result doesn't change. Does this filter work at all in Drupal 8.7.7? Or is there a mistake I made somewhere in the markup?
I believe that your filter is only applying to the 25 not the entire calculated value. Try something like this:
{% set calculated = data.auswahl_oder_eingabe * 202 / 1000000 * 25 %}
{{ calculated|number_format(2, ',', '.') }}

Symfony4 pluralization on translation not working

Pluralization is working partially in Symfony4.3 when I use the new ICU Format for messages.
Expected behaviour: One item found
Current behaviour: {1, plural, =0 {No items found.} one {One item found.} other {# items found.} }
Translation file works for other translations, so configuration I think is right. In translations/messagges.en.yaml
msg:
photos:
uploaded: >
{photos, plural,
=0 {No items found.}
one {One item found.}
other {# items found.}
}
And in the template there is the following line:
{{ 'msg.photos.uploaded'|trans({'photos': 1}) }}
I believe, for the ICU message format to work, the filename must be correct (more precisely, the domain must have +intl-icu appended):
https://symfony.com/doc/current/translation/message_format.html#using-the-icu-message-format
in your case, the filename should be: translations/messages+intl-icu.en.yaml according to the source above.

Twig translate a string which contains parameter

In my Twig project I use translation from .yaml files. The text which I need to translate is found in a .html.twig file and says, for example,
"My text for translation contains a {{parameter}} to translate."
I know that I can replace this whole string with a key word, for example - to_translate %parameter% to_translate2, and I can use the translation from my .yaml file like this
to_translate: "My text for translation contains a"
to_translate2: "to translate"
And the parameter will be passed. However, how can I do this without breaking the sentence in so many parts?
Maybe I didn't get your point, but you can add as many parameters as you want ?
Yaml file:
my_translation_key: Hello %firstname%, %lastname%, welcome here !
In Twig:
{{ 'my_translation_key' | trans({
'%firstname%': 'John',
'%lastname%': 'Doe'
}) }}
If what you want is to get nested blocks in your translations, you can probably try something like this:
Yaml file:
my_translation_key: Hello %firstname%, %lastname%, %welcome% !
welcome_block: welcome %where%
In Twig:
{% set welcome = 'welcome_block' | trans({'%where%': 'here'}) %}
{{ 'my_translation_key' | trans({
'%firstname%': 'John',
'%lastname%': 'Doe',
'%welcome%': welcome
}) }}
Maybe you should try this :
{{ ('My text for translation contains a '~parameter)|trans }}
In Documentation :
~: Converts all operands into strings and concatenates them. {{ "Hello " ~ name > ~ "!" }} would return (assuming name is 'John') Hello John!.

Twig Multiplication between two decimal values

How can I multiple two decimal values in twig ?
Let's say var1 = "37.57" and var2 = "8" and I tried with
{{ var1 * var2 }}
But it multiplies only the integer value while ignoring the decimal it returns "296" which is 37 * 8.
Can you try with
{{ var1|number_format * var2|number_format }}
Maybe it doesn't work because of string format (even if string format should work).
Doc for number_format
The integer result may be produced if wrong decimal separator is used.
Okay I got it working.
For some reason the twig is considering it as a "string" instead of "interger" not sure why it is, since i simple return the data that i receive through external API connection.
here is the thing which worked for me:
{% set var_1 = 0 + var1|numberformat(2,'.',',') %}
{% set var_2 = 0 + var2|numberformat(2,'.',',') %}
then,
{{ (var_1 * var_2)|numberformat(2,'.',',')}}

Resources