Drupal8 Twig - convert string to integer

12,271

Solution 1

try that

{{ diff["#markup"]|number_format(2,',') }}

It works for me.

Solution 2

I had a similar issue - I had to add '#markup' to get it to work.

 {{items[0].content['#markup']|number_format/5*100}}

Solution 3

stripping off tags was what did the trick for me!

{% set diff = field_goals_for|striptags - field_goals_against|striptags %}
{{ diff }}
Share:
12,271
ciaobetty
Author by

ciaobetty

Updated on June 04, 2022

Comments

  • ciaobetty
    ciaobetty about 2 years

    I just started using twig in drupal8. I'm trying to calculate the difference between two numerical drupal8 variables using views.

    field_goals_for: 24
    field_goals_against: 3
    field_goals_difference: should return 21 but returns 1
    

    I tried already something like this (with and without number_formats):

    {% set diff = field_goals_for|number_format - field_goals_against|number_format %}
    {{ diff }}
    

    I assume the problem is that the two variables are strings instead of int.

    There is a way to convert them to int and return the correct result using twig? If not do you have any alternative solution to suggest?

    EDIT: I tried to SUM and also MULTIPLE the two values:

    {{ field_goals_for }} = 24
    {{ field_goals_against }} = 3
    {{ field_goals_for - field_goals_against }} = 0
    {{ field_goals_for + field_goals_against }} = 2
    {{ field_goals_for * field_goals_against }} = 1
    

    Why are they considered equal to 1 instead of their real value?

    EDIT 2: I found the problem. The value that has been to used is field_goals_for__value instead of field_goals_for. Unfortunately I can't find a way to used both of them in the same text field.

  • ciaobetty
    ciaobetty over 7 years
    Thanks a lot, your solution works perfectly on twig but not in my drupal environment. I think the problem is related to that, but I can't figured out why it's not working properly.
  • Matteo
    Matteo over 7 years
    hi @ciaobetty very strange, check also this example with string variable and check that same result. Try check the REAL value of the two variable BEFORE the diff in order to exclude the value are different instead of the configuration
  • ciaobetty
    ciaobetty over 7 years
    unfortunately I already checked them, I printed {{ field_goals_for }} and {{ field_goals_against }} before the subtraction and they returns 24 and 3 and are stored in a Number (integer) drupal field.
  • ciaobetty
    ciaobetty over 7 years
    I have version 1.24.0