Is it legal to do this in a node template with Drupal 8?

{% set percentVariable = content.field_my_customfield.0 * 100 / content.field_my_second_customfield.0 %}

which will be output like this

<div style="width:{{ percentVariable }}{{'%'}}"></div>

Both fields deliver integer values to that variable

Is there any major syntax error or misunderstanding in doing so?

  • 1
    You really should do this in a preprocess hook and pass this variable along instead of put it in twig.
    – Kevin
    Oct 15, 2017 at 23:20
  • I really don't understand, is that supposed to give an error for some reason? Only Math between integers is allowed and not variables? stackoverflow.com/questions/9269622/… this thread seems to confirm it should be possible!
    – Oscara32
    Oct 15, 2017 at 23:28
  • 2
    Again, I would stress to do this from a preprocess hook where you have PHP available to do such operations and not rely on twig. Anyway, this is likely an error for you because you are using the render array variable and not the raw value from the node field object. The question you linked to uses simple variables to do the addition; content.field_name vars are not simple variables. Such things are just easier to create as a new variable and pass into the template to be printed out. Easier to debug, easier to reason about.
    – Kevin
    Oct 15, 2017 at 23:39
  • drupal.org/docs/7/theming/overriding-themable-output/… is this what you're referring to? Is that still valid for Drupal 8?
    – Oscara32
    Oct 16, 2017 at 0:08

1 Answer 1


Yes, it is legal to do mathematical operations in Twig (and in PHP as well). The issue you have is you are trying to calculate render arrays, which doesn't work, no matter which programming language you use. You need to do this on the field values. For example the first value you are looking for:

in PHP:

$value = $node->field_my_customfield->value;

or in Twig:

{% set value = node.field_my_customfield.value %}

This code should work then in Twig:

{% set percentVariable = node.field_my_customfield.value * 100 / node.field_my_second_customfield.value %}
<div style="width:{{ percentVariable|round }}%"></div>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.